Skip to main content

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

OperatorActionExample
++increases the variable's value by 1i++i = i + 1
--decreases the variable's value by 1i--i = i - 1

But it's important: depending on the placement (++i or i++), 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.

javascript
let i = 5; let result = ++i; // first i = 6, then 6 is returned console.log(i); // 6 console.log(result); // 6

In 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.

javascript
let i = 5; let result = i++; // first returns 5, then increases i to 6 console.log(i); // 6 console.log(result); // 5

In other words:

  • It returns the old value.
  • Only then does it change the variable.

Difference in an example

javascript
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); // 2

In expressions

This difference is especially noticeable when the operator is used inside an expression:

javascript
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
FormVariable changeReturned value
++iIncreases immediatelyNew value
i++Increases afterwardOld value
--iDecreases immediatelyNew value
i--Decreases afterwardOld value

In loops

Usually the i++ form is used in loops, because the expression's result is not used explicitly:

javascript
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

FormWhen it changesWhat it returnsExample result
++iImmediatelyNew valuelet i=1; console.log(++i)2
i++AfterOld valuelet i=1; console.log(i++)1
--iImmediatelyNew valuelet i=3; console.log(--i)2
i--AfterOld valuelet i=3; console.log(i--)3

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.