Introduction
An else-if ladder helps you check many conditions one by one. It runs the code for the first true condition it finds.
An else-if ladder helps you check many conditions one by one. It runs the code for the first true condition it finds.
if (condition1) { // code to run if condition1 is true } else if (condition2) { // code to run if condition2 is true } else if (condition3) { // code to run if condition3 is true } else { // code to run if none of the above conditions are true }
Conditions are checked from top to bottom.
Only the first true condition's code runs, then the ladder stops.
let age = 20; if (age < 13) { console.log('Child'); } else if (age < 20) { console.log('Teenager'); } else { console.log('Adult'); }
let score = 85; if (score >= 90) { console.log('Grade A'); } else if (score >= 75) { console.log('Grade B'); } else if (score >= 50) { console.log('Grade C'); } else { console.log('Fail'); }
This program checks the temperature and prints a message about the weather.
let temperature = 30; if (temperature > 35) { console.log('It is very hot today.'); } else if (temperature > 25) { console.log('The weather is warm.'); } else if (temperature > 15) { console.log('It is a bit chilly.'); } else { console.log('It is cold outside.'); }
Make sure conditions do not overlap in a confusing way.
The else part is optional but useful for handling all other cases.
Use else-if ladder to check multiple conditions in order.
Only one block of code runs: the first true condition.
It helps make decisions with many options clearly and simply.
else if ladder do in JavaScript?else if with a space, not elseif or missing parentheses.let score = 75;
if (score >= 90) {
console.log('A');
} else if (score >= 80) {
console.log('B');
} else if (score >= 70) {
console.log('C');
} else {
console.log('F');
}let num = 10;
if (num > 10) {
console.log('Greater than 10');
} else if num > 5 {
console.log('Greater than 5');
} else {
console.log('5 or less');
}let score = 45;
if (score < 0) {
console.log('Invalid');
} else if (score >= 50) {
console.log('Pass');
} else {
console.log('Fail');
}Pass the test and this pattern moves unknown