javascript - Assignment along with Post increment - Stack Overflow

I am a bit confused with the output. Tried in Javascriptvar x = 1;x = x++;console.log(x); Its outpu

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 into x. x++ returns the value of x 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
Add a ment  | 

2 Answers 2

Reset to default 8

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 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

相关推荐

  • javascript - Assignment along with Post increment - Stack Overflow

    I am a bit confused with the output. Tried in Javascriptvar x = 1;x = x++;console.log(x); Its outpu

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信