By the end of this lesson, you will know how to handle multiple choices using else if and switch statements in JavaScript.
In programming, you often need to make decisions based on different conditions. For example, imagine you are deciding what to wear based on the weather. If it is sunny, you wear a t-shirt. If it is rainy, you wear a raincoat. You can use else if and switch statements to create similar logic in your code.
else ifFile: weather.js
const weather = "sunny";
if (weather === "sunny") {
console.log("Wear a t-shirt.");
} else if (weather === "rainy") {
console.log("Wear a raincoat.");
} else if (weather === "cold") {
console.log("Wear a jacket.");
} else {
console.log("Check the weather!");
}
Wear a t-shirt.
This code checks the value of the weather variable. If the value is “sunny”, it prints “Wear a t-shirt.” If it is “rainy”, it prints “Wear a raincoat.” If it’s “cold”, it prints “Wear a jacket.” Finally, if none of these conditions are true, it shows “Check the weather!”
switch StatementYou can also use a switch statement to handle multiple choices. Here’s how it looks:
File: weather_switch.js
switch (weather) {
case "sunny":
console.log("Wear a t-shirt.");
break;
case "rainy":
console.log("Wear a raincoat.");
break;
case "cold":
console.log("Wear a jacket.");
break;
default:
console.log("Check the weather!");
}
Wear a t-shirt.
In this example, the switch statement checks the weather value against each case. Each case ends with break to stop further checking.
Now it’s your turn! Create a program that tells what activity to do based on the day of the week. If it’s Monday, suggest working. If it’s Saturday, suggest relaxing.
const day = "Saturday";
switch (day) {
case "Monday":
console.log("Time to work!");
break;
case "Saturday":
console.log("Let’s relax!");
break;
default:
console.log("Just another day!");
}
break statement: If you forget break, the code will run through to the next case. Always add break to avoid this.= instead of === can cause logical errors. Always use === for equality checking.else if for multiple conditions.switch statement is great for checking one variable against many options.