Decrementing (--)

suggest change

The decrement operator (--) decrements numbers by one.

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.

Common Uses

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, both x-- and --x reassign to x such that x = 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents