+ 1

Basic JS Question: Assigning x++ as values of variable y

Hi, this is a very basic question but it’s driving me nuts. Would be extremely thankful for a new perspective/explanation that can make me understand the error in my thought process! let x = 1; let y = x++; console.log(y) —> result is 1, but I would expect y to be 2 as in: let y = x + 1 —> let y = 1+1; on the other hand, console.log(x) results in 2; why? I declared the new value for y, not x. I’m so confused. Please help!

20th Jan 2023, 12:36 PM
SAH
SAH - avatar
5 Respuestas
+ 5
x++ will increment x when line or statement ends, so: y = x++ is y = x (and then will x be x + 1 ) And in new line if we log x we get x = 2 but y = 1 We also can have y = ++x if you use this than it will first add 1 to x and than assign value to variable y(like you expected), but x++ will first assign to y and than add 1 to x. Order matters.
20th Jan 2023, 1:02 PM
PanicS
PanicS - avatar
+ 2
Thank you!! Now the first result in loops with x++ actually also make more sense!
20th Jan 2023, 2:02 PM
SAH
SAH - avatar
+ 2
In loop x++ and ++x will be same, because how loop work. for(let x = 1; i <= 10; x++) { } We first declare variable Then compare to check do we need to run loop Then run loop Then we do whatever is at third place here is x++, but it can be x = x + 10 Than again we check condition..... So even if we place ++x this will run at end and have same effect Here is more about this operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment Here is example with for loop: We can use both i++ and ++i for loop will always run this code at end and because it is end of statement it will always increment or decrement if we use (i--) Most people use i++ not ++i, you can also use i = i + 1, note that we need here equal sign https://code.sololearn.com/WWiXmW8yKnse/?ref=app
20th Jan 2023, 2:42 PM
PanicS
PanicS - avatar
+ 2
Know this by heart If the incremental operator comes after a variable, the operation affects only the variable and otherwise. Let's say let x = 1; let y= x++; // console.log(x) = 2 // console.log(y) = 1 let a = 1; let b = ++a; //console.log(a) = 2 //console.log(b) = 2 I hope this helps. Cheers!
20th Jan 2023, 6:24 PM
Uchenna Chukwuba
Uchenna Chukwuba - avatar
+ 1
Oh wow, this is so helpful!! Thank you!!
20th Jan 2023, 3:11 PM
SAH
SAH - avatar