if-else if-else: Multiple Conditional Branches
The if-else if-else statement is a powerful way to handle multiple conditions in JavaScript. It allows you to create a sequence of checks, executing different blocks of code depending on which condition is true.
1. Basic Structure
The general structure of an if-else if-else statement is:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false AND condition2 is true
} else if (condition3) {
// Code to execute if condition1 and condition2 are false AND condition3 is true
} else {
// Code to execute if ALL previous conditions are false
}
if (condition1): The first condition is checked. If it'strue, the code block inside theifis executed, and the rest of theif-else if-elsestatement is skipped.else if (condition2): Ifcondition1isfalse, thencondition2is checked. If it'strue, its code block is executed, and the rest is skipped. You can have multipleelse ifblocks.else: If all the precedingifandelse ifconditions arefalse, the code block inside theelseis executed. Theelseblock is optional.
2. How it Works
JavaScript evaluates the conditions in order, from top to bottom. As soon as it finds a condition that evaluates to true, it executes the corresponding code block and then skips the rest of the if-else if-else chain. If none of the conditions are true, and an else block is present, the else block is executed.
3. Examples
Let's see some practical examples.
Example 1: Grading System
Example 2: Time of Day Greeting
Example 3: Multiple Conditions with Logical Operators
You can combine multiple conditions using logical operators (&&, ||, !) within the if and else if statements.
4. Importance of Order
The order of else if conditions is crucial. The first condition that evaluates to true will have its code block executed, and the rest will be skipped. Therefore, you should arrange your conditions logically.
Example: Incorrect Order
Example: Correct Order
Exercise: if-else if-else Challenges
Solve the following challenges using if-else if-else statements. Log the result to the console for each.

