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:


Arithmetic Math:
* Decrementing (--)

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
18 Arithmetic Math
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde