Can someone explain why this code outputs 4? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone explain why this code outputs 4?

var a = 6, b = 3, z = (++a - b) / (a % b); document.write(z); The way I see it is that a is that the variable a is pre-incremented and becomes 7 and is subtracted by b (which is 4), giving 3. It is then divided by 6 mod 3 (which should be zero), and If you were to divide 3 by 0, it should output infinity. Can someone explain what I'm doing wrong here?

12th Apr 2017, 8:49 AM
Andy
3 Answers
+ 8
first: (++a - b) is gonna be 4 after that a become 7. then: (a % b) is going to be 1 finally: 4 / 1 gives us 4
12th Apr 2017, 9:01 AM
Babak
Babak - avatar
+ 3
(7-3)/(7%3) = 4/1 = 4
12th Apr 2017, 9:04 AM
Yaroslav Pieskov
Yaroslav Pieskov - avatar
+ 3
Thank you for the replies! Realized what I did wrong was that I forgot the fact that the variable retains it's added value if used with pre- and post-increments/decrements.
12th Apr 2017, 7:51 PM
Andy