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.
One way of increasing the score would be to just add a value to it.
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, +=.
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:
The following code will multiply the value of score by —or, in other words, double it:
We can also divide the current ...