+ 3

Reassignment operators and post-increment

I'm toying with a timed JavaScript Challenge and want to make sure I understand this correctly. var x = 0; for(; x < 2; x++) { x += x - x++; } console.log(x); // Output is 2 1.) If x is less than 2, keep going. 2.) x += x(0) - x++(0), x now equals 0. 3.) Increment x by 1. 4.) x is less than 2, keep going. 5.) x += x(1) - x++(1), x now equals 1. 6.) Increment x by 1. 7.) x is not less than 2, exit out of the loop. Am I understanding this right?

9th Jan 2019, 3:46 AM
DumbledoresAmy
DumbledoresAmy - avatar
9 Respostas
+ 2
1. You can add console log at beginning of for loop and end of for loop to check the change of variable in each iteration. Like this: https://code.sololearn.com/W6Nf9QAk71xP/?ref=app 2. The increment of x++ in x += line is not effective because after it increments x, x is replaced by (original x+0)
9th Jan 2019, 4:21 AM
Gordon
Gordon - avatar
+ 3
Gordon Thank you, that's interesting! I really appreciate it!
9th Jan 2019, 4:24 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 3
In your new code, The reason that your for loop run only once is because when you z = x++, x is already incremented by 1 after z is 0, so you can see in the iteration, pre x is 1 already. The reason that post y and post z is 0 is, because they are assigned before for loop, y stores value of x which is 0, z also stores value of z which is 0. And in the for loop, they are called as value, especially z, it is not behaving as x++ in the for loop. Your original intention, if I have not misunderstand you, should be like this : https://code.sololearn.com/Wz6Yu57Th04c/?ref=app Notice the use anonymous function to execute the update of x every time when the function z is called.
9th Jan 2019, 5:45 AM
Gordon
Gordon - avatar
+ 2
You are welcome, DumbledoresArmy. Please allow me to emphasize the use of console log during the process of functions in debugging. This is a demo I coded for another Q&A to explain how to find out bug. https://code.sololearn.com/WuBzocc861ZK/?ref=app By the way, I am a Harry Potter fans too
9th Jan 2019, 4:41 AM
Gordon
Gordon - avatar
+ 2
I used console.log in my own test code but my specific question was if the math right of the equal sign was always equal to 0 or if something else was happening. I'm not debugging because this is a challenge question I am trying to follow through. https://code.sololearn.com/WnAsePgfjJBv/?ref=app
9th Jan 2019, 4:49 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 2
Gordon, that's it, I'm naming my patronus after you! 😊
9th Jan 2019, 6:48 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 2
🤣🤣🤣🤣🤣 Expecto Patroooonum! 🧙‍♂️
9th Jan 2019, 6:57 AM
Gordon
Gordon - avatar