Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
A switch statement is like a multiple choice menu. Instead of many if-else statements, you check one value against many options and do different things for each match!
const day = 'Monday';
if (day === 'Monday') {
console.log('Start of week');
} else if (day === 'Tuesday') {
console.log('Second day');
} else if (day === 'Wednesday') {
console.log('Midweek');
} else if (day === 'Thursday') {
console.log('Almost Friday');
} else if (day === 'Friday') {
console.log('Last workday!');
} else {
console.log('Weekend!');
}const day = 'Monday';
switch (day) {
case 'Monday':
console.log('Start of week');
break;
case 'Tuesday':
console.log('Second day');
break;
case 'Wednesday':
console.log('Midweek');
break;
case 'Thursday':
console.log('Almost Friday');
break;
case 'Friday':
console.log('Last workday!');
break;
default:
console.log('Weekend!');
}switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no match
}switch (expression)What to check
case value:Each possible value
break;Stop here (important!)
default:If nothing matches
break, code keeps running into the next case. Always add break unless you want that!Check a value against multiple options
Put multiple case statements together (no break between them) to run the same code for different values
const day = 'Saturday';
switch (day) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
console.log('Workday');
break;
case 'Saturday':
case 'Sunday':
console.log('Weekend!');
break;
}
// Output: Weekend!Multiple cases sharing the same code
Handle different states with switch
switch (num) {
case 1:
console.log('One');
// Missing break!
case 2:
console.log('Two');
break;
}If num is 1, both "One" AND "Two" will print because there's no break!
Always include default to handle unexpected values. It's like the "else" of switch statements!
Check one value against many options
Stops execution, prevents fall-through
Stack cases to share the same code
Catch all unexpected values