} else if (age < 18) {
An if / else picks between two paths. Real life often has more than two: a cinema
charges kids one price, students another and adults a third. For that you chain
else if between them.
let age = 10;
let price;
if (age < 4) {
price = 0;
} else if (age < 18) {
price = 5;
} else {
price = 10;
}
JavaScript asks the questions from the top down. age < 4? No. age < 18? Yes, so
price becomes 5 and the rest of the chain is skipped.
let temperature = 30;
if (temperature > 25) {
wearShorts();
} else if (temperature > 15) {
wearJeans();
} else {
wearCoat();
}
30 > 15 is true too, but it doesn't matter. As soon as one condition is true, its
branch runs and JavaScript jumps past the whole chain. Exactly one branch runs, never two.
let points = 95;
let grade;
if (points >= 50) { // wrong order
grade = "pass";
} else if (points >= 90) { // can never be reached
grade = "excellent";
}
95 >= 50 is true, so the chain stops there and grade is "pass". Anyone with 90 also
has 50, so the >= 90 branch can never run. Put the strictest check first:
if (points >= 90) {
grade = "excellent";
} else if (points >= 50) {
grade = "pass";
}
else Is Optional
The else at the end catches everything nobody else did. Leave it off and, if no condition
is true, nothing in the chain runs:
let total = 40;
let discount = 0;
if (total >= 100) {
discount = 20;
} else if (total >= 50) {
discount = 5;
}
// total is 40, so discount stays 0
ifs?Use a chain when only one answer is right: one grade, one price, one box size.
Use separate ifs when several things can all be true at once, and each should happen:
if (temperature > 25) {
packSunscreen();
}
if (isRaining) {
packUmbrella();
}
A hot, rainy day packs both. In a chain, the umbrella would never get packed on a hot day.