Decrementing (--)
suggest changeThe decrement operator (--) decrements numbers by one.
- Used after
n(n--), the operator returns the current value and then decrementsn. - Used before
n(--n), the operator decrementsnand then returns the new value.
let a = 5; // 5
const b = a--; // 5
const 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.
let a = 5; // 5
const b = --a; // 4
const 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 (let i = 42; i > 0; --i) {
console.log(i)
}
The update expression’s value is ignored, so --i and i-- change i the same way. The prefix form does not avoid allocating a temporary.
-- and ++ are assignments, not ordinary arithmetic operators. Aside from the value they return, both x-- and --x do x = x - 1.
const x = 1;
console.log(x--) // TypeError: Assignment to constant variable.
console.log(--x) // TypeError: Assignment to constant variable.
// --3 and 3-- are SyntaxErrors: Invalid left-hand side expression in prefix/postfix operation.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents