Programs need to make decisions: show an error if a password is too short, give a discount on large orders, greet the user differently in the morning. JavaScript makes these decisions with if, else if, else and switch. To use them well you also need to know which values JavaScript treats as true and which as false, because conditions do not have to be real booleans.
In this lesson you will learn
- How
if,else ifandelsechoose a path - How
switchcompares one value against many cases - Why
breakorreturnmatters in a switch - Truthy and falsy values
if, else if and else
function grade(marks) {
if (marks >= 80) {
return "A+";
} else if (marks >= 70) {
return "A";
} else if (marks >= 60) {
return "A-";
} else if (marks >= 40) {
return "Pass";
} else {
return "Fail";
}
}
for (const m of [91, 74, 63, 45, 22]) {
console.log(m, "->", grade(m));
}
Output
91 -> A+
74 -> A
63 -> A-
45 -> Pass
22 -> Fail
- The condition goes in parentheses. If it is true, the block in braces runs and the rest of the chain is skipped.
- Conditions are checked from top to bottom, so order matters. Because 91 passes the first test, it never reaches the later ones. If
marks >= 40came first, every passing mark would be graded “Pass”. elsehas no condition. It catches everything not matched above it.- Returning from inside each branch, as
grade()does, is a common and readable pattern.
switch and Truthy/Falsy Values
function dayType(day) {
switch (day) {
case "Friday":
case "Saturday":
return "Weekend";
case "Sunday":
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
return "Workday";
default:
return "Unknown day";
}
}
console.log(dayType("Friday"), dayType("Monday"), dayType("Funday"));
const samples = [
["0", 0], ['""', ""], ["null", null], ["undefined", undefined],
["NaN", NaN], ["false", false], ['"0"', "0"], ['" "', " "],
["[]", []], ["{}", {}], ["-1", -1],
];
for (const [label, value] of samples) {
console.log(label.padEnd(9), value ? "truthy" : "falsy");
}
Output
Weekend Workday Unknown day
0 falsy
"" falsy
null falsy
undefined falsy
NaN falsy
false falsy
"0" truthy
" " truthy
[] truthy
{} truthy
-1 truthy
switchcompares one value with eachcaseusing strict equality (===).- Stacking cases with no code between them, as with Friday and Saturday, lets several values share one result.
- When a case matches, execution continues downwards until a
breakorreturn. Forgettingbreakcauses “fall-through” into the next case. Here each case returns, so nobreakis needed. defaultruns when no case matches.
In a condition, any value is accepted. Exactly these values count as falsy: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", a string with a space, empty arrays and empty objects. That lets you write if (name) { ... } to check that a string is not empty.
if/else, switch or Ternary?
| Use | When |
|---|---|
if / else if / else | Ranges and mixed conditions, such as marks bands |
switch | One value compared against many fixed options |
cond ? a : b | Choosing between two values in a single expression |
Common Mistakes
- Wrong order of conditions, so a general test catches values meant for a specific one.
- Missing
breakin a switch, running the next case by accident. - Expecting an empty array to be falsy. Check
arr.length === 0instead. - Writing
if (x == 1 || 2); the2on its own is always truthy. Writex === 1 || x === 2.
Practice Exercises
Exercise 1. Print “Good morning” before 12, “Good afternoon” before 18, otherwise “Good evening”, using new Date().getHours().
Show answer
const hour = new Date().getHours();
if (hour < 12) {
console.log("Good morning");
} else if (hour < 18) {
console.log("Good afternoon");
} else {
console.log("Good evening");
}
Exercise 2. Write a switch that turns 1, 2 and 3 into “Gold”, “Silver” and “Bronze”, and anything else into “No medal”.
Show answer
function medal(place) {
switch (place) {
case 1: return "Gold";
case 2: return "Silver";
case 3: return "Bronze";
default: return "No medal";
}
}
Frequently Asked Questions
Can I leave out the braces for a one-line if?
Yes, if (ok) run(); is valid, but adding a second line later without braces is a classic bug. Most style guides recommend always using braces.
Does switch work with strings?
Yes. It compares with ===, so it works with strings, numbers and any other values. The match is case-sensitive.
Summary
if/else if/elserun the first branch whose condition is true.switchmatches one value against cases with===; end cases withbreakorreturn.- Only eight values are falsy; everything else, including
[]and"0", is truthy.
Next: JavaScript Loops.
