Page 68 - JavaScript
P. 68
• If used as a postfix to n, the operator returns the current n and then assigns the decremented
the value.
• If used as a prefix to 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.
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.
Exponentiation (Math.pow() or **)
b
Exponentiation makes the second operand the power of the first operand (a ).
var a = 2,
b = 3,
c = Math.pow(a, b);
c will now be 8
https://riptutorial.com/ 25

