0

javascript: switch with for and without break 🤨

var x = 0, y = 0; for(i=0; i<=2; i++){ x=i; switch(x){ case 0: y=100; case 1: y+=10; case 2: y+=1; } document.write(y); //solution: 123 How is this running and be calculated? //y=100 . that is the only thing which is clear. // case1 result: 120. where is this coming from?

18th Dec 2019, 7:50 PM
Mylisa_beth
Mylisa_beth - avatar
3 Respuestas
+ 3
I can partly explain (I think). The first time around, case 0 is executed and y is set to 100. Then (and this is the bit I don't fully understand) as there is no break statement, the rest of the case blocks appear to be executed even though they don't satisfy the case. This means, after the first iteration, y is 111. On the second iteration, case 1 is satisfied, so 10 is added to y and, again as there is no break statement, case 2's block is also executed, so now y is 122. Then the third iteration causes y to be incremented by 1 and y finishes as 123. In summary: use the break statement!
18th Dec 2019, 9:00 PM
Russ
Russ - avatar
+ 2
As you are not using break, it falls through. What happens is: i = 0 y = 100 y += 10 y += 1 //y = 111 i = 1 y += 10 y += 1 //y = 122 i = 2 y += 1 //y = 123
18th Dec 2019, 9:01 PM
Deroman
Deroman - avatar
+ 1
thank you so much!!! now i understand that this will run through all falls. thanks for your help!!! 👍👍👍💪
18th Dec 2019, 9:06 PM
Mylisa_beth
Mylisa_beth - avatar