Increment and decrement
The ++ and -- operators are increment and decrement,
and they are often confused precisely because of the difference between the prefix and postfix forms.
Let's go through everything in detail.
What the ++ and -- operators do
| Operator | Action | Example |
|---|---|---|
++ | increases the variable's value by 1 | i++ → i = i + 1 |
-- | decreases the variable's value by 1 | i-- → i = i - 1 |
But it's important: depending on the placement (
++iori++), the result of the expression can be different.
Prefix form (++i, --i)
First it changes the variable's value, then it returns the new value.
let i = 5;
let result = ++i; // first i = 6, then 6 is returned
console.log(i); // 6
console.log(result); // 6In other words:
- It increases/decreases the variable.
- It returns the new value.
Postfix form (i++, i--)
First it returns the old value, then it changes the variable.
let i = 5;
let result = i++; // first returns 5, then increases i to 6
console.log(i); // 6
console.log(result); // 5In other words:
- It returns the old value.
- Only then does it change the variable.
Difference in an example
let a = 1;
console.log(a++); // 1 → first logs, then increases
console.log(a); // 2
let b = 1;
console.log(++b); // 2 → first increases, then logs
console.log(b); // 2In expressions
This difference is especially noticeable when the operator is used inside an expression:
let x = 10;
let y = x++ + 5; // y = 10 + 5 = 15, then x = 11
let a = 10;
let b = ++a + 5; // a = 11, b = 16| Form | Variable change | Returned value |
|---|---|---|
++i | Increases immediately | New value |
i++ | Increases afterward | Old value |
--i | Decreases immediately | New value |
i-- | Decreases afterward | Old value |
In loops
Usually the i++ form is used in loops,
because the expression's result is not used explicitly:
for (let i = 0; i < 5; i++) {
console.log(i);
}There is no difference here between
i++and++i, because the returned value is not used.
Summary
| Form | When it changes | What it returns | Example result |
|---|---|---|---|
++i | Immediately | New value | let i=1; console.log(++i) → 2 |
i++ | After | Old value | let i=1; console.log(i++) → 1 |
--i | Immediately | New value | let i=3; console.log(--i) → 2 |
i-- | After | Old value | let i=3; console.log(i--) → 3 |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.