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.

Press + to interact
let score = 0;
console.log(score);

One way of increasing the score would be to just add a value to it.

Press + to interact
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 1010.

There’s a shorthand for doing this, called the compound assignment operator, +=.

Press + to interact
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 55 like so:

Press + to interact
score -= 5;
console.log(score);

The following code will multiply the value of score by 22 ...

Get hands-on with 1400+ tech skills courses.