Javascript Switch Case
Switch Case in javascript¶
In javascript switch case is an alternative to multiple if else
conditions. It allows us to write less code and still get the same functionality as if else
condtions.
Switch case syntax¶
switch(choice) {
case choice_1:
// code block
break;
case choice_2:
// code block
break;
default:
// code block
}
- default: If the given cases are not matched then it will execute the default statement.
- break: We use the
break
statement to stop execution of switch block once the case/choice is matched. If no break statement is specified then it executes all the cases and default also.
Switch case example¶
Let's write a simple switch case to print the price of a fruit
const expr = 'Papayas';
switch (expr) {
case 'Oranges':
console.log('Oranges are $0.59 a pound.');
break;
case 'Mangoes':
case 'Papayas':
console.log('Mangoes and papayas are $2.79 a pound.');
// expected output: "Mangoes and papayas are $2.79 a pound."
break;
default:
console.log(`Sorry, we are out of ${expr}.`);
}