Table of contents
What is switch statement?
It is used for implementing a conditional construct to make logical decision.
Some of the characteristics are
The switch statement takes an expression which is evaluated matching a series of case clauses
The case clause should have break statement as the last instruction else the control will fall through
The case clause can have only 1 value
The case clause can have value of any type
The default clause will be executed when any of the cases don't match
Use Cases
Case 1: Using switch case - fall through and grouping cases - without break.
// Fall through and Grouping cases
let a=2+2;
switch(a) {
case 3:
console.log("three");
case 4:
console.log("four"); // no break - the control falls through
case 2+2+1: // expression can be given as case
console.log("five");
case 7: // grouping cases
case 8:
case 9:
console.log("nine");
default:
console.log("default"); // even default executed
}
Case 2: Comparison is always strict.
// comaparision is always strict
let b="4";
switch(b) { // not converted to number
case 4:
console.log("number : 4");
break;
case "4":
console.log("string :4") ; // output
break;
default:
console.log("default");
}
Case 3: Instruction in case clause. The case clause is executed but statements inside the case clause are not executed.
let c="4";
switch(c) { // all case executes , not the statements inside
case console.log("JS"):
console.log("JS2");
case console.log("Py"):
console.log("Py2");
default:
console.log("Cpp"); // executed
}
Complete Code Listing
let a=2+2;
switch(a) {
case 3:
console.log("three");
case 4:
console.log("four"); // no break - the control falls through
case 2+2+1: // expression can be given as case
console.log("five");
case 7: // grouping cases
case 8:
case 9:
console.log("nine");
default:
console.log("default"); // even default executed
}
// comaparision is always strict
let b="4";
switch(b) { // not converted to number
case 4:
console.log("number : 4");
break;
case "4":
console.log("string :4") ; // output
break;
default:
console.log("default");
}
// Other scenarios
let c="4";
switch(c) { // all case executes , not the statements inside
case console.log("JS"):
console.log("JS2");
case console.log("Py"):
console.log("Py2");
default:
console.log("Cpp");
}
// 2
c= undefined;
switch(c) { // undefined
case undefined:
console.log("Undefined");
break;
case undefined:
console.log("Undefined2");
default:
console.log("default");
}
// 3
c=4;
switch(c) { // a, 4, d
case console.log("a"), console.log(c):
console.log("c");
default :
console.log("d");
}