0

JavaScript: Switch statement

Could someone please explain why in a Switch statement when a CASE is matched (if a BREAK is not included), the code will continue through the remainder of the CASE statements even if their arguments aren't satisfied. For example: EXAMPLE 1: var x = 0, y = 0; for (i=0;i<=2;i++) { x = i; switch(x) { case 0: y = 100; break case 1: y+=10; break case 2: y+=1; } } document.write(y); The result of the above code would be 111 However, if the 'break' lines are removed, the result of the code would be 123. What is the purpose behind this? I was under the assumption that a switch statement was used in place of a nested if statement. But without the breaks, this is no longer replicating the results of a nested if statement. Could you please provide a contextual example of when this would be useful in day to day programming? Thank you for the help! PS: I realise that occasionally in my post, my jargon is perhaps incorrect. Please, could you correct me where I am wrong so that I can learn for the future?

19th Mar 2018, 4:57 PM
Paul van Schalkwyk
Paul van Schalkwyk - avatar
2 Respostas
+ 2
"break" keyword could be used in both "for" loop and "switch" statements... so "break" inside a "switch" statement doesn't "break" your "for" loop, as it is related to the "switch" statement block and not to the "for" loop. If your purpose is to break the "for" loop, you need to rather use "if/else" statements instead of a "switch" one... In a "switch" block statement, when a "case" satisfy the equality with the variable used as parameter (inside the parenthesis), all next instruction in the block are executed until it encouter a "break" keyword, even if next "case" doesn't satisfy the equality, so: switch (x) { case 0: document.write("x is zero"); case 42: document.write("the answer of all questions is 42"); } ... will only write the second sentence if x equal 42, but will write both sentences if x equal zero ;)
20th Mar 2018, 1:52 AM
visph
visph - avatar
+ 1
switch is similar to if else conditions and can be implemented if there are many cases instead of writing if else statements follow the link for more info https://www.w3schools.com/js/js_switch.asp
19th Mar 2018, 5:06 PM
kaliki chandu
kaliki chandu - avatar