There are various ways to write if statements, and the switch statement is a convenient one in many cases. It can replace the need to write multiple if statements. The switch statement checks multiple cases and compares it to a given value. Then it executes the code in each corresponding case block. The switch statement can also have an optional default.
The switch statement will save quite a few keystrokes, and in some scenarios, can be easier to read than multiple if, if else statements.
It starts off with the switch keyword and takes in the argument of the variable whose value we'll be checking the cases against.
let fruit = "orange";
switch(fruit) {
case "apple":
console.log(`I have an ${fruit}.`);
break;
case "orange":
console.log(`I'd like a glass of ${fruit} juice.`)";
break;
case "mango":
console.log(`I'll try some ${fruit} slices today.`);
break;
case "pear":
console.log(`I enjoy ${fruit}s more than I do apples.`);
break;
default:
"I'll take any fruit.";
}
function checkFruit(fruit) {
if (fruit === "apple") {
console.log(`I have an ${fruit}.`);
}
else if (fruit === "orange") {
console.log(`I'd like a glass of ${fruit} juice.`);
}
else if (fruit === "mango") {
console.log(`I'll try some ${fruit} slices today.)`;
}
else if (fruit === "pear") {
console.log(`I enjoy ${fruit}s more than I do apples.`);
}
else {
console.log(`I'll take any fruit.`);
}
}
The last default case in the switch statement acts as the else statement in the if/else if statement. If none of the cases match the value being provided, then the switch statement will console log "I'll take any fruit.".
The switch statement also uses colons :
, not semi-colons ;
to create different cases, please be mindful of that syntax.
The break
keyword is necessary in the switch statement to ensure the code stops running once the case matches the value. Otherwise, the switch statement will run every case.
The switch statement can prove useful in a variety of scenarios. You're likely to make fewer errors using a switch statement than multiple if/if else statements. It's important to be comfortable with if/if else statements before using the switch statement. The switch statement is not a replacement for the if/if else statement syntax, but rather an additional way to write if statements when you have multiple cases.
Top comments (0)