Making Decisions: if / else
beginner12 min readLesson 30 of 143
Programs that choose: if, else if, and else β how code takes different paths based on data.
So far every line of your code has run. Conditionals let programs choose.
if / else if / else
const score = 87;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("Keep practicing");
}
The conditions are checked top to bottom; the first truthy one wins and the
rest are skipped. The final else catches everything the earlier branches
missed.
Truthiness
Conditions do not need to be booleans β JavaScript converts them:
- Falsy:
false,0,""(empty string),null,undefined,NaN - Truthy: everything else β including
"0","false", and[]
const name = ""; // falsy!
if (name) {
console.log("Hello, " + name);
} else {
console.log("Please enter your name");
}
This pattern β if the value exists, use it, otherwise handle the missing case β is everywhere in real code.
Nesting and combining
const age = 15;
const withAdult = true;
if (age >= 18 || withAdult) {
console.log("You can enter");
} else {
console.log("Sorry, adults only");
}
Prefer combining conditions with &&/|| over deep nesting β flat
reads better.
What you learned
if/else if/else: first matching branch wins- Falsy values:
false, 0, "", null, undefined, NaN - Combine conditions with logical operators instead of nesting deeply
Next: doing things repeatedly β loops.