How Do the Increment and Decrement Operators Work?
Lesson Overview
The increment (`++`) and decrement (`--`) operators in JavaScript are shorthand methods for increasing or decreasing a variable's value by 1.
The increment (++) and decrement (--) operators in JavaScript are shorthand methods for increasing or decreasing a variable’s value by 1.
Basic Usage
Instead of writing x = x + 1 or x = x - 1, you can use these operators:
- Increment:
x++(or++x) - Decrement:
x--(or--x)
Prefix vs. Postfix
The most important distinction is where you place the operator: prefix (before the variable) or postfix (after the variable). This affects when the value is updated if the operator is used as part of a larger expression.
1. Prefix (++x or --x)
“Increment/Decrement first, then use the value.” The variable is updated immediately, and the new value is returned for the expression.
let x = 5;
console.log(++x); // Output: 6
console.log(x); // Output: 6
In this example, x becomes 6 before it is passed to console.log.
2. Postfix (x++ or x--)
“Use the value first, then increment/decrement.” The current value is used in the expression, and the variable is updated after that operation is complete.
let y = 5;
console.log(y++); // Output: 5
console.log(y); // Output: 6
In this example, console.log uses the original value (5) first. Only after that line is executed does y become 6.
Summary
- Prefix (
++x/--x): Change value first, then return the new value. - Postfix (
x++/x--): Return the current value, then change it. - When used on their own (not inside a larger expression), there is no difference in the final result.