Lesson 5 of 34 · Fundamentals
JavaScript if/else Statements and Comparison Operators
So far your programs have run every line, every time. Real programs make decisions: open the door if the player has the key, show "Game Over" when health hits zero, give a bonus on weekends.
In this lesson you'll learn how JavaScript compares values and chooses which code to run.
Comparison operators
Comparisons produce a boolean: true or false.
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(4 <= 3); // false
console.log(5 === 5); // true (strictly equal)
console.log(5 !== 3); // true (strictly not equal)
Always use === and !==
JavaScript also has == and !=, which convert types before comparing, with surprising results:
console.log("5" == 5); // true (the string is converted to a number)
console.log(0 == ""); // true (!)
console.log("5" === 5); // false (different types)
The strict operators === and !== never convert types, so they do what you expect. Use them by default.
if, else if and else
An if statement runs a block of code only when its condition is true:
const hp = 0;
if (hp === 0) {
console.log("Game over!");
}
Add else for the other case, and else if for more branches. JavaScript checks the conditions from top to bottom and runs only the first branch that matches:
function describeHealth(hp) {
if (hp <= 0) {
return "Defeated";
} else if (hp < 30) {
return "Wounded";
} else {
return "Healthy";
}
}
console.log(describeHealth(10)); // Wounded
Because return leaves the function immediately, you'll often see the else keywords dropped: each if returns, so later lines only run when earlier conditions were false.
Combining conditions: &&, || and !
a && b(AND) is true when both are true.a || b(OR) is true when at least one is true.!a(NOT) flips a boolean.
const level = 12;
const hasKey = false;
console.log(level >= 10 && hasKey); // false
console.log(level >= 10 || hasKey); // true
console.log(!hasKey); // true
Use parentheses when mixing them, so the intent is obvious: isAdmin || (isMember && hasPaid).
Truthy and falsy
if doesn't strictly need a boolean. Any value is treated as either truthy or falsy. These values are falsy: false, 0, "" (empty string), null, undefined and NaN (plus the rarely seen -0 and 0n). Everything else is truthy, including "0", "false" and -1.
const nickname = "";
if (nickname) {
console.log(`Hi, ${nickname}`);
} else {
console.log("Hi, stranger"); // this runs: "" is falsy
}
The ternary operator
For a quick either/or value, use condition ? valueIfTrue : valueIfFalse:
const gold = 120;
const status = gold >= 100 ? "rich" : "poor";
console.log(status); // rich
Common mistakes
=instead of===.if (hp = 0)assigns 0 instead of comparing it.- Chaining comparisons.
1 < x < 10doesn't mean "x is between 1 and 10". Writex > 1 && x < 10. - Wrong branch order. In
if (xp < 500) … else if (xp < 100) …the second branch can never run, because the first one already caught every value below 500.
Assignment
Complete two functions:
getRank(xp)returns a rank based on experience points:"Invalid"ifxpis negative"Novice"for 0–99 XP"Adept"for 100–499 XP"Master"for 500 XP or more
canEnterDungeon(level, hasKey)returnstrueif the hero may enter: heroes of level 10 or higher can always enter, and heroes of level 5 to 9 can enter only ifhasKeyistrue. Everyone else is turned away (false).
Examples: getRank(150) returns "Adept", canEnterDungeon(7, true) returns true.
If/else and conditions in other languages
- Python If, Elif and Else Statements · Python
- Go if/else and switch Statements · Go
- Java if/else and switch Statements · Java
- C# if/else, switch and Switch Expressions · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .