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

pushpesh kumarpushpesh kumar
3 min read

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:

  • ++xPrefix increment

  • x++Postfix increment

Spoiler: Both increase the value by 1, but they return different results.


🧠 The Core Difference

SyntaxNameIncrements the value?Returns…
++xPrefix✅ YesThe new value after increment
x++Postfix✅ YesThe 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 ++aa 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-casePreferred FormWhy?
Counting loopsEither worksIf return value isn’t used
Assign-and-increment++xYou want the updated value
Log-and-incrementx++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 effectSame effect
When used in assignment?Returns incremented valueReturns original value
0
Subscribe to my newsletter

Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

pushpesh kumar
pushpesh kumar