The
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases...
default:
// Code to execute if none of the cases match expression
}
Here's a simple example of a
let day = 'Wednesday';
switch (day) {
case 'Monday':
console.log('It\'s Monday!');
break;
case 'Tuesday':
console.log('It\'s Tuesday!');
break;
case 'Wednesday':
console.log('It\'s Wednesday!');
break;
default:
console.log('It\'s some other day.');
}
You can also use nested
let meal = 'lunch';
let food = 'sandwich';
switch (meal) {
case 'breakfast':
switch (food) {
case 'cereal':
console.log('Enjoy your cereal for breakfast.');
break;
case 'toast':
console.log('Enjoy your toast for breakfast.');
break;
default:
console.log('What are you having for breakfast?');
}
break;
case 'lunch':
switch (food) {
case 'sandwich':
console.log('Enjoy your sandwich for lunch.');
break;
case 'salad':
console.log('Enjoy your salad for lunch.');
break;
default:
console.log('What are you having for lunch?');
}
break;
default:
console.log('What time is your meal?');
}
The