switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
var color = "red";
switch (color) {
case "blue":
console.log("color is blue");
break;
case "white":
console.log("color is white");
break;
case "black":
console.log("color is black");
break;
case "red":
console.log("color is red");
break;
default:
console.log("color doesn't match ")
}
//Output: color is red;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
console.log(day);
switch(expression) {
case x:
// code of block to be executed when this case matches
break; // if you decide to run a return statement in a specific case, then don't write break
case y:
// code of block to be executed when this case matches
return "xyz"
// In this case no "break" will be written as we have written a return statement
default: "xyz" // If no case matches then the code written in the block of "default" will be executed
}
// For example
let x = 5;
switch(x) {
case 1:
console.log(`x value is ${x}`)
case 2:
console.log(`x value is ${x}`)
case 3:
console.log(`x value is ${x}`)
case 4:
console.log(`x value is ${x}`)
case 5:
console.log(`x value is ${x}`)
}
// Output "x value is 5"
switch (new Date().getDay()) { // input is current day
case 6: // if (day == 6)
text = "Saturday";
break;
case 0: // if (day == 0)
text = "Sunday";
break;
default: // else...
text = "Whatever";
}
switch(variable/expression) {
case value1:
// body of case 1
break;
case value2:
// body of case 2
break;
case valueN:
// body of case N
break;
default:
// body of default
}