+ 1
Increment/Decrement problem
What is the output of this code? var x = 9; var y = 3; var z = (--x - ++y) % y; document.write(z); The answer is 0 How is this 0 and not 1? What I got in the parenthesis is (8 - 4) which equals to 4 and then 4 % 3 = 1.
7 Answers
+ 5
https://www.sololearn.com/discuss/100584/?ref=app
https://www.sololearn.com/discuss/44929/?ref=app
https://www.sololearn.com/discuss/721629/?ref=app
https://www.sololearn.com/discuss/203689/?ref=app
https://www.sololearn.com/discuss/1077/?ref=app
https://www.sololearn.com/discuss/436945/?ref=app
https://www.sololearn.com/discuss/1182526/?ref=app
https://www.sololearn.com/discuss/322142/?ref=app
https://www.sololearn.com/discuss/489143/?ref=app
+ 3
++y doesn't just return y+1, it also increases y by 1. Once you called --x, the variable because equal to 8, and once you called ++y, that variable became equal to 4. Therefore, it evaluated (8 - 4) % 4.
+ 2
Not just the rest of the problem, but it stays incrememted by one. If you don't want that, it's better to use (y+1) instead of ++y.
+ 1
Zone As Daniel C noted, the confusion was probably (++y), which not only increases the value of 'y' within the parentheses but of the actual variable itself š
Once you get it, you won't get hung up again š
var x = 9;
var y = 3;
var z = (--x - ++y) % y;
>> (8 - 4) % 4
>> (4 ) % 4
>> 0
document.write(z);
>> z = 0
0
Daniel C so is it correct to say that once you've changed the variable , that number gets used for the rest of the problem?
0
Daniel C okay thanks
0
will yeah, I was still using 3 for y outside the parenthesis instead of 4. I didn't know the variable stays at 4 once you've changed it