Increment/Decrement problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

2nd Nov 2019, 9:59 PM
Zone
Zone - avatar
7 Answers
+ 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.
2nd Nov 2019, 10:02 PM
Daniel C
Daniel C - avatar
+ 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.
2nd Nov 2019, 10:15 PM
Daniel C
Daniel C - avatar
+ 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
2nd Nov 2019, 10:19 PM
will
will - avatar
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?
2nd Nov 2019, 10:13 PM
Zone
Zone - avatar
0
Daniel C okay thanks
2nd Nov 2019, 10:18 PM
Zone
Zone - avatar
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
2nd Nov 2019, 10:23 PM
Zone
Zone - avatar