0

I somewhat understand the reasoning in the comment for why y is equal to 4, but I don't understand why when the variable y is declared with x++ it doesn't increment it and assign 3 instead of just taking the previous declared value?

// In this line: var y = x++ the value of x is assigned to y before x is incremented, 
// so y equals 3 on line 2, while x equals 4. 
// Therefore on line 3, y now equals 4 instead of 5.

var x = 3;
var y = x++;
y += 1;
Barmar
  • 741,623
  • 53
  • 500
  • 612
Pat8
  • 958
  • 9
  • 19
  • 1
    Assign 3 to what? Sorry, it's not really clear what part of the code you don't understand, or what result you would have expected instead. – Bergi Oct 09 '19 at 23:58
  • 2
    `y += 1` adds 1 to `y`. So if it was 3 before, now it's 4. – Barmar Oct 09 '19 at 23:59
  • var y =x++; is just a shortcut for var y =x; x++; – AllirionX Oct 10 '19 at 00:01
  • Possible duplicate of [How do the post increment (i++) and pre increment (++i) operators work in Java?](https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java) or [Post-increment and Pre-increment concept](https://stackoverflow.com/q/4445706/69809). – vgru Oct 10 '19 at 00:05
  • I don't understand the question. You ask why it doesn't assign 3, instead of taking the previous declared value, but 3 *is* the previous value. – Barmar Oct 10 '19 at 00:16

1 Answers1

2

It has to do with where you're placing your ++. The way ++ works (it's just the syntax of it) is that if you use it after x the code will increment the y variable, but the expression then returns the value BEFORE it increments x (so it'll just return the value of x). What you want is for the incrementation to occur FIRST. So the code below should work in incrementing the value because it will first increment, then return the variable.

let x = 3;
let y = ++x;
y += 1;

console.log(y); // Returns 5
paoiherpoais
  • 334
  • 1
  • 10