Variable Manipulation
Learn how to manipulate a variable using different operators.
Varying variables
If a variable has been assigned a numerical value, it can be modified using different operators. For example, say we’re making a game that keeps track of the number of points we’ve scored in a variable called score
. First of all, we’d initialize the score
to zero.
let score = 0;console.log(score);
One way of increasing the score
would be to just add a value to it.
score = score + 10;console.log(score);
This will increase the value held in the score
variable by 10
.
The notation can seem strange at first, because the left-hand and right-hand sides are not equal, but remember that the =
symbol is used for assignment, and we’re assigning the score
variable to its current value plus another .
There’s a shorthand for doing this, called the compound assignment operator, +=
.
score += 10;console.log(score);
There are equivalent compound assignment operators for all the arithmetic operators that we saw in the previous section. For example, we can decrease the score
by like so:
score -= 5;console.log(score);
The following code will multiply the value of score
by ...
Get hands-on with 1400+ tech skills courses.