In JavaScript, the switch statement is used to execute different blocks of code based on the value of an expression. It’s a more concise and readable way to handle multiple conditions than using multiple if statements.
Here’s an example of a switch statement:
const fruit = "apple";
switch (fruit) {
case "banana":
console.log("This is a banana.");
break;
case "apple":
console.log("This is an apple.");
break;
case "orange":
console.log("This is an orange.");
break;
default:
console.log("I don't know what fruit this is.");
}
In this example, the switch statement checks the value of the fruit variable. If the value is “banana”, the code inside the first set of curly braces is executed. If the value is “apple”, the code inside the second set of curly braces is executed. If the value is “orange”, the code inside the third set of curly braces is executed. If the value doesn’t match any of the cases, the code inside the default block is executed.
Note that the break statement is used after each case to exit the switch statement and prevent execution of the code in the subsequent cases. Without the break statement, the code would continue executing through all the cases, even if the matching case has already been found.
You can also use the switch statement with expressions other than strings, such as numbers or boolean values. In addition, you can nest switch statements inside other control flow statements, such as if statements, to create more complex logic.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.