The decrement operator (--
) decrements numbers by one.
n
, the operator returns the current n
and then
assigns the decremented the value.n
, the operator assigns the decremented n
and
then returns the changed value.var a = 5, // 5
b = a--, // 5
c = a // 4
In this case, b
is set to the initial value of a
. So, b
will be 5, and c
will be 4.
var a = 5, // 5
b = --a, // 4
c = a // 4
In this case, b
is set to the new value of a
. So, b
will be 4, and c
will be 4.
The decrement and increment operators are commonly used in for
loops, for example:
for (var i = 42; i > 0; --i) {
console.log(i)
}
Notice how the prefix variant is used. This ensures that a temporarily variable isn't needlessly created (to return the value prior to the operation).
Note: Neither
--
nor++
are like normal mathematical operators, but rather they are very concise operators for assignment. Notwithstanding the return value, bothx--
and--x
reassign tox
such thatx = x - 1
.const x = 1; console.log(x--) // TypeError: Assignment to constant variable. console.log(--x) // TypeError: Assignment to constant variable. console.log(--3) // ReferenceError: Invalid left-hand size expression in prefix operation. console.log(3--) // ReferenceError: Invalid left-hand side expression in postfix operation.