Every program is a sequence of decisions. JavaScript gives you two ways to make them. There is if and else for open-ended branching, and there is switch for matching one value against a known list. Both of them have rules that are not obvious until you meet them, especially the way that switch falls through from one case into the next, and the way that an else if ladder grows deeper than anybody intended.
The previous lesson in this module covered "The Ternary Operator and Short-Circuiting", and the next lesson in this module is about "Loops: for, while and Their Modern Patterns".
What is the basic shape of an if/else?
There are three keywords, and they come in this order. There is if with a condition, then an optional else if with another condition, and then an optional else for everything that is left over.
function shippingCost(weightKg, express) {
if (express) {
return 120;
} else if (weightKg > 10) {
return 60;
} else {
return 30;
}
}
console.log('light normal:', shippingCost(5, false));
console.log('heavy normal:', shippingCost(12, false));
console.log('light express:', shippingCost(5, true));
Only the first matching branch runs. Once a condition turns out to be true, its block is executed and the rest of the chain is skipped completely. That is why an else if that is placed before a more specific test will hide it completely.
One structural detail is worth knowing early. A let or a const that you declare inside a block belongs to that block, and you cannot read it from outside of it.
function pickSize(quantity) {
if (quantity > 10) {
const discount = 0.2;
return 'bulk, ' + (discount * 100) + '% off';
}
return 'standard';
}
console.log('twelve:', pickSize(12));
console.log('two:', pickSize(2));
Why are guard clauses better than an else-if ladder?
An else if chain nests the happy path at the bottom of an indentation staircase. Every extra rule pushes the main case further down and further to the right. Guard clauses turn that around. Each rule states its own condition and then leaves immediately, so the remaining path stays at the left margin where it is easy to read.
// A ladder: the interesting case sits at the bottom of a pyramid.
function priceLadder(user, cart) {
if (user) {
if (cart.length > 0) {
if (user.member) {
return cart.subtotal * 0.9;
} else {
return cart.subtotal;
}
}
}
return 0;
}
// Guards: every rule is one flat line.
function priceGuards(user, cart) {
if (!user) {
return 0;
}
if (cart.length === 0) {
return 0;
}
if (user.member) {
return cart.subtotal * 0.9;
}
return cart.subtotal;
}
console.log('ladder gives', priceLadder({ member: true }, { length: 1, subtotal: 100 }));
console.log('guards give', priceGuards({ member: true }, { length: 1, subtotal: 100 }));
Both of them give 90. The second version has no nesting at all, and every line reads as a complete rule on its own. This is the single most effective readability improvement that is available to a beginner, and it costs nothing except the habit of writing if (condition) { return value; } and moving on.
How does switch work?
switch takes one expression and compares it against a list of case values. The first match wins, and break stops the engine from carrying on past it.
function planLabel(plan) {
switch (plan) {
case 'free':
return 'Up to 5 projects';
case 'pro':
return 'Unlimited projects';
case 'team':
return 'Unlimited projects plus 10 seats';
default:
return 'Unknown plan';
}
}
console.log('pro:', planLabel('pro'));
console.log('team:', planLabel('team'));
console.log('gold:', planLabel('gold'));
Notice that every case ends with a return, which leaves the function before any break could matter. That is a perfectly good pattern. When every branch returns a value, the break becomes unnecessary.
The default branch handles everything that matched nothing. It is optional, but it is worth including whenever the input comes from outside your program. A switch on a plan name should have a default, because plans get renamed from time to time, and a missing case should be visible rather than silent.
What is fallthrough, and when is it useful?
If you leave out the break, the engine keeps running into the next case. That is usually a mistake, and occasionally it is exactly what you want.
// A deliberate fallthrough: two cases share one body.
function classify(code) {
let label = '';
switch (code) {
case 200:
case 201:
label = 'success';
break;
case 404:
label = 'not found';
break;
default:
label = 'other';
}
return label;
}
console.log('200:', classify(200));
console.log('404:', classify(404));
console.log('500:', classify(500));
The stacked case 200: and case 201: with nothing between them mean that either of those values runs this block. That is the legitimate use of a fallthrough, where several inputs share one outcome.
The illegitimate use is an accidental fallthrough, where a missing break lets one case run the code of the next case as well. Here is how you can see the difference.
function auditLog(code) {
const entries = [];
switch (code) {
case 400:
entries.push('client error');
case 401:
entries.push('needs auth');
break;
case 500:
entries.push('server error');
break;
}
return entries;
}
console.log('400 gives', auditLog(400));
console.log('500 gives', auditLog(500));
For the code 400 the function records two entries, because the missing break let the 400 case fall through into the 401 case. For the code 500 it records only one. If that was not what you wanted, then the fix is one break. Many style guides also ask you to write a // falls through comment wherever a fallthrough is deliberate, so that the next reader knows it was a decision and not a slip.
Why does switch use strict comparison?
Because the comparison inside a switch always uses ===. The number 2 does not match the case '2', and the text '2' does not match the case 2.
console.log('2 === "2":', 2 === '2');
switch (2) {
case '2':
console.log('matched the text');
break;
default:
console.log('no match, because switch uses ===');
}
switch ('free') {
case 'free':
console.log('free plan');
break;
default:
console.log('other plan');
}
This is the reason that a switch on a value from a form or from a URL will quietly land in default when the type is not what you expected. The fix is the same as it is everywhere else. Normalise the input before you switch on it, with String(value) or with Number(value).
Which should you use?
| Situation | Reach for |
|---|---|
| A range of conditions, or a condition that is not a simple equality test | if and else with guard clauses |
| One value matched against a known list | switch |
| A single yes-or-no choice that produces a value | A ternary |
| More than about three branches of equal weight | switch, or a lookup object |
- Only the first matching branch runs, so order your conditions from the most specific to the least.
- A
letthat is declared inside a block stays inside that block. - Prefer guard clauses with early returns over deep
else ifladders. switchcompares with===, so2and'2'are different cases.- A missing
breakcauses a fallthrough. Use stacked cases deliberately, and comment them. - Always give a
switchover external input adefaultbranch.
Try it yourself: write a describeStatus(code) function that maps HTTP status codes to a message. Use switch with stacked cases for the success range from 200 to 299, and a default for anything else. Then deliberately remove one break and run it against a code in that range to watch the fallthrough happen. Put the break back, and finish by converting the whole thing to a lookup object, so that you can see when that approach reads better.