JavaScript - decrement operator
The decrement (--) is an unary operator in JavaScript and hence acts upon a single operand to produce a new value. It has two variant:
- Pre-decrement: Decreases the value of the operand by 1, then returns the operand.
- Post-decrement: Returns the operand, then decreases the value of the operand by 1.
Example: Pre-decrement operator
The example below describes the usage of pre-decrement operator.
var x = 10; var y = 20; var z, txt; //below expression is equivalent to //x = x - 1; z = x + y; z = --x + y; txt = "x = " + x + "<br>"; txt = txt + "y = " + y + "<br>"; txt = txt + "z = " + z + "<br>";
The output (value of txt) after running above script will be:
x = 9 y = 20 z = 29
Example: Post-decrement operator
The example below describes the usage of post-decrement operator.
var x = 10; var y = 20; var z, txt; //below expression is equivalent to //z = x + y; x = x - 1; z = x-- + y; txt = "x = " + x + "<br>"; txt = txt + "y = " + y + "<br>"; txt = txt + "z = " + z + "<br>";
The output (value of txt) after running above script will be:
x = 9 y = 20 z = 30
❮ JavaScript - Operators