If-Else Ladder
An "if-else ladder" refers to a series of if
, else if
, and possibly a final else
statement, where each if
or else if
condition is evaluated sequentially. If a condition is true, the corresponding block of code is executed, and subsequent conditions are skipped. If no condition is true, the code inside the else
block (if present) is executed.
Example:
let num = 5;
if (num > 0) {
console.log("Positive number");
} else if (num < 0) {
console.log("Negative number");
} else {
console.log("Zero");
}
In this example:
- If
num
is greater than 0, the first block of code is executed, and the subsequentelse if
andelse
blocks are skipped. - If
num
is less than 0, the first condition is false, but the second condition (num < 0
) is true, so the corresponding block is executed, and theelse
block is skipped. - If neither condition is true (i.e.,
num
is 0), the first two blocks are skipped, and the code inside theelse
block is executed.
Extending the Ladder:
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else if (score >= 60) {
console.log("D");
} else {
console.log("F");
}
In this example, the code checks the value of score
against multiple conditions to determine the corresponding grade.
It's important to note that in an if-else ladder, only the block associated with the first true condition is executed. Subsequent conditions are not evaluated once a true condition is found. The else
block (if present) is executed only if none of the previous conditions is true.