Increment and decrement operations in JavaScript
Consider the following code:
let num = 0;
num = num + 1; // add the number 1 to the variable num
alert(num); // shows 1
As you already know, this code can be
rewritten in an shortened form through
the operator +=
:
let num = 0;
num += 1; // add the number 1 to the variable num
alert(num); // shows 1
In fact, adding one in programming is so
common that an even more shortend syntax
has been invented for this operation -
the special operator increment ++
,
which increases the value of a variable by 1
.
Let's rewrite our code with it:
let num = 0;
num++; // add the number 1 to the variable num
alert(num); // shows 1
There is also the operation decrement
--
, which decreases the value
of a variable by 1
.
See an example:
let num = 0;
num--; // subtract the number 1 from the variable num
alert(num); // shows -1
Modify this code such a way that it contains increment and decrement operations:
let num = 10;
num = num + 1;
num = num + 1;
num = num - 1;
alert(num);