0
What would switch() statement would if two cases have the same condition
4 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;
}
+ 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
+ 5
Russ Thanks a lot for mentioning it. đ
Its a very important point i missed.