JavaScript ++x vs x++: Prefix vs Postfix Increment Explained

If you’ve seen ++
before or used it to increment a counter in JavaScript, you might not realize that where you place it actually changes the behavior.
Let’s dive into the difference between:
++x
→ Prefix incrementx++
→ Postfix increment
Spoiler: Both increase the value by 1
, but they return different results.
🧠 The Core Difference
Syntax | Name | Increments the value? | Returns… |
++x | Prefix | ✅ Yes | The new value after increment |
x++ | Postfix | ✅ Yes | The original value before increment |
✅ Example 1: Using in isolation
let x = 5;
++x;
console.log(x); // 6
x++;
console.log(x); // 7
Here, both increase x
by 1. So what's the big deal? 🤔
The difference becomes clear when you use the result immediately.
⚠️ Example 2: Using in assignments
let a = 5;
let b = ++a; // Prefix: increment first, then assign
console.log(a); // 6
console.log(b); // 6
let c = a++; // Postfix: assign first, then increment
console.log(a); // 7
console.log(c); // 6
🧠 Prefix ++a
→ a
becomes 6
, and b
gets 6
🧠 Postfix a++
→ a
becomes 7
, but c
gets the old value 6
🔄 Visual Flow
let x = 3;
// Postfix: use → then update
let y = x++; // y = 3, x = 4
// Prefix: update → then use
let z = ++x; // x = 5, z = 5
📦 Practical Use Cases
Use-case | Preferred Form | Why? |
Counting loops | Either works | If return value isn’t used |
Assign-and-increment | ++x | You want the updated value |
Log-and-increment | x++ | You want to log before incrementing |
🧪 In a for
loop?
Both forms are fine when you're only incrementing:
for (let i = 0; i < 5; i++) {
console.log(i);
}
for (let i = 0; i < 5; ++i) {
console.log(i);
}
💡 No real performance or behavioral difference unless you're using the return value of the increment.
✅ Summary
Feature | ++x (Prefix) | x++ (Postfix) |
Increments value? | ✅ Yes | ✅ Yes |
Returns… | New value (after increment) | Old value (before increment) |
When used standalone? | Same effect | Same effect |
When used in assignment? | Returns incremented value | Returns original value |
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
