In this lesson, we will learn about the javascript switch statement and how to use it. In a switch statement, an expression is evaluated, its value is matched to a case clause, and statements associated with that case, as well as those in the following cases, are executed. The javascript switch statement is specially used in decision-making scenarios.
Syntax,
switch(expression) {
case a:
// code block
break;
case b:
// code block
break;
default:
// code block
}
The switch statement checks the expression inside the parentheses and executes the case according to the value of the expression. If no matching cases are found then the default case is executed.
Different examples of Javascript Switch Statement
Example 1: Basic switch case
switch (instrument) {
case "guitar":
console.log("I play the guitar");
break;
case "piano":
console.log("I play the piano");
break;
default:
console.log("I don't play an instrument");
break;
In the above example, if the value of the instrument is guitar
then the output will be I play the guitar
. Similarly, if the value of the instrument is piano
then the output will be I play the piano
. If the value does not include guitar or piano then the output will be I don't play an instrument
.
Example 2: MIssing break statement
If the break statement is removed from the switch case statement then the next case along with the matching case will be executed.
switch (instrument) {
case "guitar":
console.log("I play the guitar");
case "piano":
console.log("I play the piano");
break;
default:
console.log("I don't play an instrument");
break;
In the above example, if the value of the instrument is the guitar the output will be
I play the guitar
I play the piano
Example 3: Switch with multiple cases
switch (animal) {
case "lion":
case "tiger":
case "wolf":
console.log("I love wild animal");
break;
default:
console.log("I don't love animal");
break;
In the above example, the output will be I love wild animal
if the value of the animal is among lion, tiger, or wolf.
Conclusion
In this article, we learn about the javascript switch statement and how to use it with the help of some examples. To learn more about javascript visit here.