Lesson 36 of 296
if, else, switch and the ternary operator
What you will learn
- How a program makes decisions with
if elseandelse if- Blocks and curly braces
- Guard clauses (early return)
switch- The ternary operator
On this page
if
if runs a block of code only when a condition is true.
const age = 20;
if (age >= 18) {
console.log("You can vote.");
}- The condition goes inside the round brackets
( ). - The code to run goes inside the curly braces
{ }. This is called a block. - If the condition is false, the block is skipped.
if ... else
else runs when the condition is false.
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are too young to vote.");
}Exactly one of the two blocks runs, never both, never neither.
else if: more than two choices
const score = 72;
if (score >= 70) {
console.log("Distinction");
} else if (score >= 60) {
console.log("Merit");
} else if (score >= 40) {
console.log("Pass");
} else {
console.log("Fail");
}JavaScript checks the conditions from top to bottom and runs only the first one that is true. Here it prints "Distinction" and stops, even though 72 is also above 60 and 40.
Order matters. If you put score >= 40 first, everyone who passed would get "Pass".
Truthy and falsy in conditions
The condition does not have to be a boolean. Any value works, using truthy and falsy (Lesson 35):
const name = "";
if (name) {
console.log("Hello " + name);
} else {
console.log("Please enter your name.");
}"" is falsy, so the else block runs.
Careful: 0 is falsy too. If 0 is a valid value (a price, a quantity, a score), check it directly:
if (quantity !== undefined) { ... } better than if (quantity)Always use curly braces
JavaScript allows an if with no braces for a single line:
if (isAdmin) console.log("Admin");But if you later add a second line, it will not be part of the if. Always use braces. Most team style rules require them.
Guard clauses
Deeply nested if blocks are hard to read:
function checkout(user, basket) {
if (user) {
if (basket.length > 0) {
if (!user.isBlocked) {
console.log("Processing order");
}
}
}
}A guard clause checks the bad cases first and leaves the function early with return:
function checkout(user, basket) {
if (!user) return;
if (basket.length === 0) return;
if (user.isBlocked) return;
console.log("Processing order");
}Same behaviour, much easier to read. Interviewers like this style. (Functions and return are explained in Lesson 38.)
switch
switch compares one value against many fixed options.
const day = "sat";
switch (day) {
case "sat":
case "sun":
console.log("Weekend");
break;
case "fri":
console.log("Almost the weekend");
break;
default:
console.log("Weekday");
}| Part | Meaning |
|---|---|
switch (day) | The value to check |
case "sat": | Runs if day === "sat" (strict comparison) |
break | Stops. Without it, the code falls through into the next case. |
default | Runs if no case matched, like else |
Fall-through: in the example, "sat" has no code and no break, so it falls into "sun" and prints "Weekend". This is used on purpose to group cases. Forgetting break by accident is a classic bug.
When to use switch: many fixed values for one variable, such as an order status or a menu choice. For ranges like score >= 70, use if ... else if.
The ternary operator
A short if ... else that produces a value:
condition ? valueIfTrue : valueIfFalseconst age = 20;
const label = age >= 18 ? "Adult" : "Child";Read it as: "is age 18 or more? If yes, 'Adult', otherwise 'Child'."
It is very common in template literals and in React:
const message = `You have ${count} ${count === 1 ? "item" : "items"}`;Do not nest ternaries. This is hard to read:
const grade = score >= 70 ? "A" : score >= 60 ? "B" : score >= 40 ? "C" : "F";Use if ... else if instead.
Common mistakes
=instead of===in a condition.- Conditions in the wrong order in an
else ifchain. - Forgetting
breakin aswitch. - Using
if (value)when0or""is a valid value. - Deep nesting instead of guard clauses.
- Long nested ternaries.
How to say it in an interview
"if runs a block when its condition is truthy, else if checks further conditions top to bottom and only the first match runs. I prefer guard clauses with early returns to deep nesting. switch compares one value strictly against fixed cases, and I always remember break to avoid fall-through. The ternary operator is a compact if-else expression that returns a value, but I avoid nesting it."
Key words
| Word | Meaning |
|---|---|
| Condition | An expression that decides which code runs |
| Block | Code inside curly braces { } |
| Branch | One of the possible paths in an if/else |
| Guard clause | An early check that leaves a function straight away |
| switch | Compares one value against many cases |
| Fall-through | A switch case running into the next because break is missing |
| Ternary | condition ? a : b, a short if/else that gives a value |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.