Javascript switch statement
Created By: chatGPT
The
switch
statement is a control flow statement that allows you to evaluate an expression and execute different blocks of code based on the value of that expression. It is often used to simplify the logic of multiple if-else
statements, making the code easier to read and maintain.switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
// ... More cases
default:
// Code to execute if no cases match
}
Here’s how the
switch
statement works: The expression is evaluated once, and its value is compared with the values of each case
. If there is a match, the corresponding block of code will be executed. You can use the break
statement to exit the switch
block; if omitted, the code will continue to execute in the following cases, which can lead to unintended behavior (known as 'fall-through'). The default
case is optional and will execute if none of the case
values match the expression.const fruit = 'apple';
switch (fruit) {
case 'banana':
console.log('Banana is yellow.');
break;
case 'apple':
console.log('Apple is red.');
break;
case 'grape':
console.log('Grape is purple.');
break;
default:
console.log('Fruit not found.');
}