0

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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
Aju John
  • 2,214
  • 1
  • 10
  • 27
  • 3
    The *post* in *post-increment* means it first returns the current value and *post* that increments the variable. And you’re then assigning the returned value back to the variable… – deceze Apr 04 '19 at 11:53
  • 2
    it's because you're assigning the value of `x++` back into `x`. `x++` returns the value of `x` *before* the increment, while `++x` returns the value afterwards. That's the only difference. – Robin Zigmond Apr 04 '19 at 11:53
  • Does this answer your question? [Postfix and prefix increments in JavaScript](https://stackoverflow.com/questions/49550526/postfix-and-prefix-increments-in-javascript) – Sebastian Simon Mar 09 '21 at 13:09

2 Answers2

6

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.

Salman A
  • 262,204
  • 82
  • 430
  • 521
5

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)
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
  • So the post-increment never happened? – Aju John Apr 04 '19 at 11:55
  • No, it did - its value was changed after the value was assigned, meaning that if `x = 5++`, then `x` is `5`, but the value was still increased by one, but not stored in `x`. – Jack Bashford Apr 04 '19 at 11:56
  • 2
    `x` was `2` for a brief moment between the expression `x++` having been evaluated and the assignment to `x =` having been completed… – deceze Apr 04 '19 at 11:58
  • 2
    Just refer to the official docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic _If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4._ (the answer is in the part "**whereas x++ returns 3 and, only then, sets x to 4**") – briosheje Apr 04 '19 at 11:58
  • You may imagine `++` like this: `function ++(x) { var tmp = x; x += 1; return tmp; }`… – deceze Apr 04 '19 at 11:59
  • "The assignment goes first, then the incrementing" is false – serge May 05 '22 at 15:09