Multiple Branches
An else-if ladder lets you test multiple conditions in order.
The first matching condition runs, and the rest are skipped.
JavaScript Tutorial
An else-if ladder allows you to check multiple conditions in sequence.
The first true condition runs, and the rest are skipped.
Many real-world rules have tiers or ranges. else-if ladders are perfect for those cases.
Ordering conditions correctly prevents bugs and unexpected behavior.
if (a) { ... } else if (b) { ... } else { ... }const score = 78;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
...Use ordered ranges so the first match wins.
const total = 125;
let fee;
if (total > 200) {
fee = 0;
} else if (total > 100) {
fee = 5;
} else {
fee = 10;
}
...Tiers are a common use case for else-if ladders.
An else-if ladder lets you test multiple conditions in order.
The first matching condition runs, and the rest are skipped.
Put the most specific or highest-priority conditions first.
A broad condition early can block the rest of the ladder.
If you are comparing a single value to many discrete cases, a switch can be clearer.
For ranges or complex conditions, an else-if ladder is usually better.
const status = "processing";
let label;
if (status === "paid") {
label = "Paid";
} else if (status === "failed") {
label = "Failed";
} else if (status === "processing") {
label = "Processing";
} else {
...Order the conditions by priority or specificity.
const age = 17;
const hasId = true;
let result;
if (age >= 18 && hasId) {
result = "Enter";
} else if (age >= 18) {
result = "Need ID";
} else {
result = "Too young";
...Combine logical operators when needed.
Without
let label = "";
if (score >= 90) {
label = "A";
}
if (score >= 80) {
label = "B";
}With
let label;
if (score >= 90) {
label = "A";
} else if (score >= 80) {
label = "B";
}Put the most specific or highest-priority checks first.
Ensure ranges do not overlap in unintended ways.
Consider switch or data-driven maps for large sets.
Use a final else to handle unexpected values.
The first matching condition stops evaluation of the rest.
When you need ranges or complex conditions.
It helps handle unexpected values safely.
Practice: Create a shipping tier using else-if for totals above 200, above 100, and below 100.
const total = 145;
// TODO: set fee using an else-if ladder
One Possible Solution
const total = 145;
let fee;
if (total > 200) {
fee = 0;
} else if (total > 100) {
fee = 5;
} else {
fee = 10;
}
console.log(fee);Yes, the first true condition runs and the rest are skipped.
Use switch for many discrete values of one variable.
Yes, but readability can suffer.
Adjust the score to see which branch fires.