What would switch() statement would if two cases have the same condition | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What would switch() statement would if two cases have the same condition

14th Jul 2020, 1:07 PM
Acer Eshwar
Acer Eshwar - avatar
3 Answers
+ 3
/* It depends on break statement . I suggest trying this code in playground and fiddle with it to get clearer picture on flow of control*/ const { log } = console; // Without break log("\n Without break: all matching cases are executed"); switch("hi"){ case "hi": log("- first hi"); case "hi": log("- second hi"); default : log("- third hi"); } // With breaks log("\n \nWith break: matching cases are executed until control comes out of switch block due to break \n"); switch("hi"){ case "hi": log("- first hi"); case "hi": log("- second hi"); break; default : log("- third hi"); break; }
14th Jul 2020, 1:23 PM
Morpheus
Morpheus - avatar
+ 6
Morpheus It is worth noting that, without break, ALL successive cases are executed whether they are matched or not (after a successful match). See example below. log("\n \nWith break: matching cases are executed until control comes out of switch block due to break \n"); switch("hi"){ case "not hi": log("- zeroth hi"); case "hi": log("- first hi"); case "anything": log("- second hi"); break; default : log("- third hi"); break; } // - first hi // - second hi
14th Jul 2020, 1:42 PM
Russ
Russ - avatar
+ 5
Russ Thanks a lot for mentioning it. 👌 Its a very important point i missed.
14th Jul 2020, 1:50 PM
Morpheus
Morpheus - avatar