I am a bit confused with the output. Tried in Javascript
var x = 1;
x = x++;
console.log(x); //Its output is 1
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?
Share Improve this question edited Oct 9, 2024 at 8:57 JSON Derulo 18k11 gold badges57 silver badges75 bronze badges asked Apr 4, 2019 at 11:50 Aju JohnAju John 2,2441 gold badge13 silver badges27 bronze badges 3- 5 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 ♦ Commented Apr 4, 2019 at 11:53
-
3
it's because you're assigning the value of
x++
back intox
.x++
returns the value ofx
before the increment, while++x
returns the value afterwards. That's the only difference. – Robin Zigmond Commented Apr 4, 2019 at 11:53 - Does this answer your question? Postfix and prefix increments in JavaScript – Sebastian Simon Commented Mar 9, 2021 at 13:09
2 Answers
Reset to default 8The 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 bees 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 bees 1
The above rules are described here. The rules indicate that x
is incremented before assignment, not after.
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)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745137776a4613284.html
评论列表(0条)