What you'll learn
Control flow lets the same program respond differently to different data. You will turn boolean expressions into readable decisions.
Booleans, truthiness, and falsiness
A condition does not have to be literally true or false; JavaScript converts it to a boolean. Only a small set of values is falsy.
| Falsy value | Common meaning |
|---|---|
false | A negative boolean |
0, -0, 0n | Numeric zero |
"" | Empty text |
null, undefined | Missing values |
NaN | Invalid numeric result |
console.log(Boolean("hello"));
console.log(Boolean(""));
console.log(Boolean(0));
console.log(Boolean([]));Watch out
items.length === 0 when you mean “this collection is empty.”if, else if, and else
const score = 84;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "Needs practice";
}
console.log(grade);Conditions run top to bottom and stop after the first match. Put more specific or higher thresholds first. Always use braces, even for one statement.
The conditional operator
The ternary operator chooses between two expressions: condition ? whenTrue : whenFalse.
const itemsInCart = 1;
const label = itemsInCart === 1 ? "1 item" : `${itemsInCart} items`;
console.log(label);Tip
if for multiple actions or nested decisions.switch for exact alternatives
const role = "editor";
let permission;
switch (role) {
case "admin":
permission = "manage everything";
break;
case "editor":
permission = "edit content";
break;
case "viewer":
permission = "read content";
break;
default:
permission = "no access";
}
console.log(permission);switch compares cases with strict equality. Without break, execution falls through to later cases—occasionally useful, often accidental.
Guard clauses
A guard clause handles an invalid or exceptional case early. It keeps the main path flat and easy to read.
function shippingCost(country, subtotal) {
if (!country) return "Choose a country";
if (subtotal < 0) return "Invalid subtotal";
if (subtotal >= 75) return 0;
return country === "Lebanon" ? 4 : 12;
}
console.log(shippingCost("Lebanon", 40));Mini-project: ticket decision
const age = 19;
const hasTicket = true;
const isBanned = false;
let message;
if (isBanned) {
message = "Entry denied";
} else if (age >= 18 && hasTicket) {
message = "Welcome!";
} else if (!hasTicket) {
message = "A ticket is required";
} else {
message = "Adult supervision is required";
}
console.log(message);Recap & quick check
Key takeaways
- Conditions convert values to booleans; know the short falsy list.
- if chains stop at the first matching branch.
- Use ternaries for simple value selection and switch for exact alternatives.
- Guard clauses handle exceptional cases early and reduce nesting.
Quick check
1. Which value is truthy?
2. What comparison does switch use?
3. When is a ternary clearest?
4. Why use a guard clause?