0

Why do I get "1" at the end?[SOLVED]

This is a sololearn JS challenge question. Why does the console output 1 and and not 0? code: https://code.sololearn.com/cR31C1ODc66Z/?ref=app

30th Dec 2021, 3:12 PM
Bhaveshsingh Pawar
Bhaveshsingh Pawar - avatar
6 Answers
0
ɴᴜʟʟ there post increments x++, I++ are independent tasks. So complete task is done there. Those are single instructions. Have no compound operations. So after incrementing only goes to execute next instruction, first x++, then next i++ Ex: if you have statement like console.log(x++) ; Here, it's a compound statement of having console.log for printing x and x++ so it first prints x value and then increments x value. Ex2: x=1 x++ + ++x, (1+3=4) operations done like x(using value first) , then x++, (x value updated to 2) , now ++x, (x value updated to 3) so finally 1+3=4 Hope it helps..
30th Dec 2021, 5:45 PM
Jayakrishna 🇮🇳
+ 2
Why you expect 0 ? Do you don't want loop to run? write your understandings.. Your loop runs and first iteration I=0, x incremented x++ and you have break statement immediately so loop exits. And x=1 , it's printed. If you don't have break then x=5 If you don't run or have loop then x=0
30th Dec 2021, 3:17 PM
Jayakrishna 🇮🇳
+ 1
Because you incremented x for once before breaking the loop.
30th Dec 2021, 3:15 PM
zexu knub
zexu knub - avatar
+ 1
ɴᴜʟʟ , it's completely normal. In the loop x is incremented once, then you break the loop and the variable is now 1.
30th Dec 2021, 3:16 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
zexu knub , TheWh¡teCat 🇧🇬 and Jayakrishna🇮🇳 , Sorry, I should have mentioned my understanding. x++, here it (++) is a postfix operator means it should increment after the task is done. So, on the first iteration shouldn't the x value be 0? And on second iteration 1 as incremented after operation. But as loop breaks it doesn't move on to second iteration and x remains 0.
30th Dec 2021, 4:40 PM
Bhaveshsingh Pawar
Bhaveshsingh Pawar - avatar
0
Jayakrishna🇮🇳 Yes, now I have understood thank you very much. In the loop x has incremented after the iteration. Means on printing the x with console.log() the incremented value is being printed.
31st Dec 2021, 6:39 AM
Bhaveshsingh Pawar
Bhaveshsingh Pawar - avatar