 else and else if
else and else if
When you need your code to make decisions based on more than just a simple yes or no, you use branching logic. This means your program can follow different paths depending on what's happening. A great way to picture this is to imagine a traffic light. When you approach a traffic light, you have to make a decision.
- If the light is red, you stop;
- If it's yellow, you get ready to stop;
- If it's green, you go.
In JavaScript, you can handle these different possibilities using if, else if, and else statements. This lets your code respond to many situations, not just two.
1234567891011let light = "yellow"; if (light === "red") { console.log("Stop!"); } else if (light === "yellow") { console.log("Get ready to stop."); } else if (light === "green") { console.log("Go!"); } else { console.log("Unknown signal."); }
1234567891011let light = "green"; if (light === "red") { console.log("Stop!"); } else if (light === "yellow") { console.log("Get ready to stop."); } else if (light === "green") { console.log("Go!"); } else { console.log("Unknown signal."); }
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Can you explain how the `else if` statement works in this example?
What happens if the value of `light` is something other than "red", "yellow", or "green"?
Can you show how to add more conditions to this branching logic?
Awesome!
Completion rate improved to 7.69 else and else if
else and else if
Deslize para mostrar o menu
When you need your code to make decisions based on more than just a simple yes or no, you use branching logic. This means your program can follow different paths depending on what's happening. A great way to picture this is to imagine a traffic light. When you approach a traffic light, you have to make a decision.
- If the light is red, you stop;
- If it's yellow, you get ready to stop;
- If it's green, you go.
In JavaScript, you can handle these different possibilities using if, else if, and else statements. This lets your code respond to many situations, not just two.
1234567891011let light = "yellow"; if (light === "red") { console.log("Stop!"); } else if (light === "yellow") { console.log("Get ready to stop."); } else if (light === "green") { console.log("Go!"); } else { console.log("Unknown signal."); }
1234567891011let light = "green"; if (light === "red") { console.log("Stop!"); } else if (light === "yellow") { console.log("Get ready to stop."); } else if (light === "green") { console.log("Go!"); } else { console.log("Unknown signal."); }
Obrigado pelo seu feedback!