Problem Statement
What is the difference between x++ and ++x?
Explanation
Post increment returns the current value first, then increments the variable.
Pre increment increments the variable first, then returns the new value.
The difference matters when the expression is used in an assignment or comparison.
If you just write the increment on its own line, both behave the same way.
Post increment is more commonly used in loops, but understanding the difference prevents bugs in complex expressions.
Code Solution
SolutionRead Only
// Post-increment (x++)
let a = 5;
let b = a++; // b gets 5, then a becomes 6
console.log(b); // 5
console.log(a); // 6
// Pre-increment (++x)
let x = 5;
let y = ++x; // x becomes 6, then y gets 6
console.log(y); // 6
console.log(x); // 6
// Common in loops
for (let i = 0; i < 5; i++) { // Post-increment
console.log(i); // 0, 1, 2, 3, 4
}
// In comparisons
let num = 10;
console.log(num++ === 10); // true (compares before increment)
console.log(num); // 11
let num2 = 10;
console.log(++num2 === 10); // false (increments before compare)
console.log(num2); // 11