Lesson 6 of 28
In progress
Conditions: if, switch and the ternary
Branch on values with if and switch, choose the readable form for each case, and avoid conditions that are always true.
A program that cannot choose is a script. Conditions are where behaviour starts to depend on data, and where most logic bugs live.
What you will learn
- Write
if,else ifandelsebranches in the right order. - Use
switchfor one value with many cases. - Replace deep nesting with guard clauses.
if and else
Editable. Runs in your browser.
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else if (score >= 50) {
grade = "C";
} else {
grade = "F";
}
console.log(grade);
Press Run to see the output.
Only the first true branch runs, so order the checks from most to least strict. If score >= 50 came first, a 95 would be graded C and the rest would never be reached.
The condition can be any expression. Braces are optional for a single statement, but always writing them prevents the bug where a second line looks included and is not.
Truthiness in conditions
if (value) converts the value to a boolean. That is convenient for objects and strings, and wrong when 0 or "" is a legitimate value.
Editable. Runs in your browser.
if (count) {
console.log("Has items");
} else {
console.log("count is falsy");
}
if (count !== undefined) {
console.log("count was provided");
}
Press Run to see the output.
The two checks answer different questions. Be explicit when zero, empty text or false are meaningful.
switch
switch compares one value against several cases using strict equality. It is clearer than a long else if chain when every branch tests the same variable.
Editable. Runs in your browser.
switch (command) {
case "add":
console.log("Adding a task");
break;
case "list":
console.log("Listing tasks");
break;
case "done":
console.log("Completing a task");
break;
default:
console.log("Unknown command");
}
Press Run to see the output.
break exits the switch. Without it, execution falls through to the next case, which is occasionally intentional and usually a bug. Group cases that share a branch by listing them together before one break.
JavaScript does not need break in every language, but it does here, and forgetting one is a classic source of "it ran two branches".
The ternary
The conditional operator chooses between two expressions. It is right for a small value choice and wrong for control flow.
Editable. Runs in your browser.
Press Run to see the output.
A nested ternary is hard to read. If you need two conditions, use if or a lookup object.
Editable. Runs in your browser.
Press Run to see the output.
A lookup object replaces a switch when the branches only map a key to a value. It also makes the valid keys visible in one place.
Guard clauses
Nesting makes a reader hold several conditions at once. Returning early flattens the main path.
Editable. Runs in your browser.
if (!user.name) {
return "Unnamed user";
}
return `${user.name} (${user.role ?? "member"})`;
}
console.log(describeUser(null));
console.log(describeUser({ name: "Ana" }));
Press Run to see the output.
Each guard handles one impossible case, and the successful path stays at the left edge. The same pattern works at the top of an event handler: check the element, then proceed.
Naming a condition also documents it. const isEligible = age >= 13 && hasConsent; followed by if (isEligible) reads better than a long inline expression, and the name states the rule the branch is enforcing, which is exactly what the next reader needs to check the logic quickly. The same trick turns a confusing negation into a positive statement: const isMissing = !user;.
Conditions that are always true
Two common mistakes produce a branch that never does what you think:
if (answer === "yes" || "y")is always true, because"y"is truthy. Use["yes", "y"].includes(answer).if (x = 5)assigns instead of comparing and is true whenever 5 is truthy. Strict mode does not catch this in a condition; the assignment is legal.
The second is rarer in modern code because linters flag it, but it is worth recognising in someone else’s file.
switch uses strict equality, so case 1: does not match the string "1" from an input. Convert the value before the switch, or compare strings consistently, rather than adding both cases and hoping.
Write a function that takes a role and returns its label using a lookup object, falling back to "Guest". Then write an if chain that returns a shipping cost: free above 500, 40 above 200, otherwise 60.
Show solution
Editable. Runs in your browser.
function shipping(total) {
if (total >= 500) return 0;
if (total >= 200) return 40;
return 60;
}
console.log(roleLabel("editor"));
console.log(roleLabel("owner"));
console.log(shipping(650), shipping(250), shipping(80));
Press Run to see the output.
The lookup object handles three exact matches without a switch, and the shipping function orders thresholds from highest to lowest so the first match is correct.
Recap
- Order
else ifbranches from strictest to loosest; the first true branch wins. switchneedsbreak, compares strictly, and suits many cases on one value.- Guard clauses and lookup objects keep branching readable.
Next, you will repeat work with loops, including the array iteration forms you will use daily.
Is switch faster than if?
Can a condition be a function call?
Progress is saved in this browser only. No account, no email.