Decide which case applies
Delivery is free for subtotals of 100 or more. It costs 10 below that threshold. Valid subtotals are nonnegative numbers. Predict charges for 99, 100 and 101 before execution.
const subtotal = 100;
let deliveryCharge;
if (subtotal >= 100) {
deliveryCharge = 0;
} else {
deliveryCharge = 10;
}
console.assert(deliveryCharge === 0);
if evaluates a condition. Its block runs only if the condition is truthy. else provides the alternative. Braces group statements. Both branches assign a charge, so the value is defined afterward for a valid subtotal.
More than two alternatives
const subtotal = 60;
let deliveryCharge;
if (subtotal >= 100) {
deliveryCharge = 0;
} else if (subtotal >= 50) {
deliveryCharge = 5;
} else {
deliveryCharge = 10;
}
console.assert(deliveryCharge === 5);
Only the first matching branch runs. This version introduces a new confirmed exercise policy: half-price delivery from 50 up to, but not including, 100. Checking >= 50 before >= 100 would make the free-delivery branch unreachable for large orders.
Guided review
A developer writes three independent if statements that each assign the charge. Several can run and overwrite earlier decisions. An else if chain communicates mutually exclusive categories. Independent if statements are appropriate when several actions should happen, not when one category should win.
Independent exercise
A parcel is small below 2 kg, medium from 2 up to 5 kg, and large at 5 kg or above. Use a known valid positive weight. Predict categories at 1.9, 2 and 5, then implement the chain.
Correction
The categories are small, medium and large. Check below 2 first, below 5 second, then use else. The second branch already excludes weights below 2. Negative weights remain invalid input; this classification alone does not validate them.
Review
Explain why a successful normal example is insufficient. The boundaries are where different interpretations often diverge; test them explicitly before trusting your branches.