Introduction
A switch statement helps you choose between many options easily. It makes your code cleaner when you check one value against many cases.
A switch statement helps you choose between many options easily. It makes your code cleaner when you check one value against many cases.
switch (expression) { case value1: // code to run if expression === value1 break; case value2: // code to run if expression === value2 break; // more cases... default: // code to run if no case matches break; }
The break stops the switch from running the next cases.
The default case runs if no other case matches.
day and prints a message for Monday, Friday, or any other day.switch (day) { case 'Monday': console.log('Start of the week'); break; case 'Friday': console.log('Almost weekend'); break; default: console.log('Just another day'); break; }
let color = 'red'; switch (color) { case 'blue': case 'green': console.log('Cool color'); break; case 'red': console.log('Warm color'); break; default: console.log('Unknown color'); break; }
This program checks the fruit and prints its color category.
const fruit = 'apple'; switch (fruit) { case 'banana': console.log('Yellow fruit'); break; case 'apple': console.log('Red or green fruit'); break; case 'orange': console.log('Orange fruit'); break; default: console.log('Unknown fruit'); break; }
Always use break to avoid running code in the next cases unintentionally.
The default case is optional but useful for unexpected values.
Switch works best with simple values like strings or numbers.
Switch helps pick code to run based on one value.
Use case for each option and break to stop.
default runs if no case matches.
switch statement in JavaScript?const day = 3;
switch(day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');
break;
default:
console.log('Unknown day');
}const color = 'red';
switch(color) {
case 'red'
console.log('Stop');
break;
case 'green':
console.log('Go');
break;
default:
console.log('Wait');
}Pass the test and this pattern moves unknown