Search⌘ K
AI Features

Variable Manipulation

Explore how to manipulate numerical variables in JavaScript using arithmetic operators, compound assignments, and increments. Understand variable updates with examples including score tracking and converting age from years to seconds with user input.

We'll cover the following...

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.

Javascript (babel-node-es2024)
let score = 0;
console.log(score);

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

Javascript (babel-node-es2024)
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, +=.

Javascript (babel-node-es2024)
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:

Javascript (babel-node-es2024)
score -= 5;
console.log(score);

The following code will multiply the value of score by 22—or, in other words, double it:

Javascript (babel-node-es2024)
score *= 2;
console.log(score);

We can also divide the current ...