Introduction
In JavaScript, we often need to increase or decrease a value by 1. For example, a game score may increase from 10 to 11, or the number of available seats may decrease from 10 to 9.
JavaScript provides two operators for this:
++ → Increment
-- → Decrement
Increment increases a value by 1, while decrement decreases a value by 1.
How Increment and Decrement Work
The basic idea is simple:
++ → Add 1
-- → Subtract 1
For example:
let x = 10;
x++; // 10 → 11
x--; // 11 → 10
Both operators can be placed before or after a variable. Their position determines when the value is used.
POST → Use the value first, then change it
PRE → Change the value first, then use it
This gives us four operators:
x++ → Use → +1
++x → +1 → Use
x-- → Use → -1
--x → -1 → Use
Increment Operator ++
1. Post-Increment x++
Post-increment uses the old value first, then increases the variable by 1.
let x = 5;
let y = x++;
console.log(x);
console.log(y);
Output:
6
5
Here, y gets the old value 5, and then x becomes 6.
Think of a ticket counter: give the current ticket number first, then move to the next number.
2. Pre-Increment ++x
Pre-increment increases the value first, then uses the new value.
let x = 5;
let y = ++x;
console.log(x);
console.log(y);
Output:
6
6
Here, x first changes from 5 to 6, and then y receives 6.
Decrement Operator --
1. Post-Decrement x--
Post-decrement uses the old value first, then decreases the variable by 1.
let x = 5;
let y = x--;
console.log(x);
console.log(y);
Output:
4
5
Here, y gets 5, and then x becomes 4.
2. Pre-Decrement --x
Pre-decrement decreases the value first, then uses the new value.
let x = 5;
let y = --x;
console.log(x);
console.log(y);
Output:
4
4
Here, x first changes from 5 to 4, and then y receives 4.
Easy Way to Remember
You don't need to memorize four separate definitions. Remember these two rules:
POST → USE FIRST
PRE → CHANGE FIRST
And:
++ → Increase by 1
-- → Decrease by 1
Therefore:
x++ → Use → +1
++x → +1 → Use
x-- → Use → -1
--x → -1 → Use
Increment and Decrement in Real Programs
These operators are commonly used with counters and loops.
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output:
0
1
2
3
4
Here, i++ increases the counter after each iteration.
Understanding these operators is also important for JavaScript interviews, especially output-based questions involving expressions, conditions, and loops.
Increment and decrement operators provide a short way to increase or decrease values by 1.
The most important rule to remember is:
POST → Use first
PRE → Change first
++ → Increase
-- → Decrease
Once you understand this rule, you can easily understand all four operators:
x++ ++x
x-- --x
Top comments (0)