Skip to content
Codewilds

Lesson 5 of 34 · Fundamentals

JavaScript if/else Statements and Comparison Operators

easy10 XP3 min readFree lesson

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 < 10 doesn't mean "x is between 1 and 10". Write x > 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:

  1. getRank(xp) returns a rank based on experience points:
    • "Invalid" if xp is negative
    • "Novice" for 0–99 XP
    • "Adept" for 100–499 XP
    • "Master" for 500 XP or more
  2. canEnterDungeon(level, hasKey) returns true if the hero may enter: heroes of level 10 or higher can always enter, and heroes of level 5 to 9 can enter only if hasKey is true. Everyone else is turned away (false).

Examples: getRank(150) returns "Adept", canEnterDungeon(7, true) returns true.

If/else and conditions in other languages

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+10 XP

Press Run to execute your code, or Submit to check it against the tests.