最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Assignment along with Post increment - Stack Overflow

programmeradmin0浏览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 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)

发布评论

评论列表(0)

  1. 暂无评论