Aju John
Aju John

Reputation: 2234

Assignment along with Post increment

I am a bit confused with the output. Tried in Javascript

var x = 1;
x = x++;
console.log(x); //Its output is 1

I was thinking it to be 2. because I am doing the print after the post-increment. Any views on it?

Upvotes: 2

Views: 586

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272096

The order in which x = x++ is executed is as follows:

  • Old value of x is calculated (oldValue = 1)
  • New value for x is calculated by adding 1 to old value (newValue = 2)
  • New value is assigned to x. At this point x becomes 2!
  • Old value is returned (return value is 1). This concludes the evaluation of x++
  • The old value is assigned to x. At this point x becomes 1

The above rules are described here. The rules indicate that x is incremented before assignment, not after.

Upvotes: 7

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

It's correct. The assignment goes first, then the incrementing. Compare:

var x = 1
var y = 1
x = x++
y = ++y

console.log(x, y)

Upvotes: 6

Related Questions