JavaScript if…else

Make your code decide what to do with if, else if and else.

Lesson 12 of 56Beginner13 min read

Programs need to make choices: if it's raining, show an umbrella; otherwise, show sunglasses. The if statement runs a block of code only when a condition is true, and else handles every other case.

Conditions are what make a program react to its situation instead of doing the same thing every time. Form checks, game rules, discounts, error messages and personalised greetings are all built from if statements. Writing them clearly, and in the right order, is one of the most important habits in programming.

The if statement

JavaScript
if (temperature > 25) {
  console.log("Shorts weather!");
}
  • The condition goes in round brackets.
  • The code to run goes in curly braces.
  • If the condition is false, the whole block is skipped.

The condition doesn't have to be a comparison. Any value works, and JavaScript treats it as truthy or falsy. For example, if (username) runs only when the username isn't an empty string.

else and else if

JavaScript
if (score >= 90) {
  grade = "A";
} else if (score >= 70) {
  grade = "B";
} else {
  grade = "C";
}

JavaScript checks each condition from top to bottom and runs the first block whose condition is true, then skips the rest. The final else, which has no condition, catches everything left over.

Only one block in the chain ever runs. If you need several things to happen independently, use separate if statements instead of a chain.

Combining conditions with && and ||

Use && (and), || (or) and ! (not) from Operators:

JavaScript
if (hasTicket && !isBanned) { … }
if (day === "Sat" || day === "Sun") { … }

Each side of || must be a complete comparison. Writing day === "Sat" || "Sun" is a common mistake: "Sun" on its own is always truthy, so the condition is always true.

Keeping conditions readable

Deeply nested if statements, with an if inside an if inside another if, quickly become hard to follow. Two habits help:

  • Store complicated conditions in well-named variables: const canCheckout = items.length > 0 && hasAddress;
  • Inside functions, handle the special cases first and return early, so the main code doesn't sit inside several layers of braces.

Clear conditions are easier to test and much easier to change when the rules of your app change.

JavaScript if...else Syntax

if…else if…else

if (condition1) {
  // runs if condition1 is true
} else if (condition2) {
  // runs if condition1 is false and condition2 is true
} else {
  // runs if none were true
}

JavaScript if...else Summary

  • if runs a block only when its condition is truthy.
  • else if adds more checks; else handles everything that's left.
  • Only the first matching block in a chain runs, so order conditions from most specific to least.
  • Combine conditions with &&, || and !, writing a full comparison on each side.
  • Name complex conditions and return early to avoid deep nesting.

JavaScript if...else Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Weather advice

Change temp to 30, 15 and 2, and run each time.

const temp = 15;

if (temp >= 25) {
  console.log("☀️ Hot! Sun cream and water.");
} else if (temp >= 12) {
  console.log("🌤 Mild. A light jacket will do.");
} else if (temp >= 0) {
  console.log("🧥 Cold. Wear a warm coat.");
} else {
  console.log("🥶 Freezing! Stay inside with cocoa.");
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3Checked first. 15 isn't ≥ 25, so skip.
  2. Line 515 ≥ 12 is true, so this block runs and the rest are skipped.
  3. Line 9else only runs if every condition above was false.
Example 2

Login check with combined conditions

const username = "pixel_pete";
const password = "hunter22";
const attempts = 2;

if (attempts >= 3) {
  console.log("Account locked. Try again in 10 minutes.");
} else if (username === "pixel_pete" && password === "hunter22") {
  console.log("Welcome back, Pete! 👋");
} else {
  console.log("Wrong username or password.");
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 5Check the lock first. Even a correct password shouldn't work when the account is locked.
  2. Line 7Both conditions must be true.
Example 3

Even or odd with a ternary

For simple either/or values, the ternary operator is a compact alternative.

const n = 7;

if (n % 2 === 0) {
  console.log(n + " is even");
} else {
  console.log(n + " is odd");
}

const label = n % 2 === 0 ? "even" : "odd";
console.log(`Ternary says: ${label}`);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 3 to 7A classic if/else.
  2. Line 9The same decision in one line: condition ? ifTrue : ifFalse.

Common JavaScript if...else Mistakes

Assignment instead of comparison

Don't
if (lives = 0) {
  console.log("Game over");
}
Do
if (lives === 0) {
  console.log("Game over");
}

= sets lives to 0, which is falsy. The message never shows, and you've overwritten your variable.

Wrong order in an else-if chain

Don't
if (score >= 50) { grade = "Pass"; }
else if (score >= 90) { grade = "Distinction"; } // never reached
Do
if (score >= 90) { grade = "Distinction"; }
else if (score >= 50) { grade = "Pass"; }

Semicolon after the condition

Don't
if (isAdmin); {
  deleteEverything(); // ALWAYS runs!
}
Do
if (isAdmin) {
  deleteEverything();
}

A ; right after if (…) ends the statement, so the block becomes ordinary code that always runs.

JavaScript if...else in Real Projects

Conditions everywhere

Show "Delivery included!" when the basket is over £40. Show an error if the email has no @. Show the dark logo when dark mode is on. Every app is full of if statements, and keeping them simple and in the right order is a core programming skill.

JavaScript if...else Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the condition.

const age = 20;
 (age >= 18) {
  console.log("Adult");
}  {
  console.log("Minor");
}
Predict the outputmedium

What does this print?

const x = 12;
if (x > 5) {
  console.log("A");
} else if (x > 10) {
  console.log("B");
} else {
  console.log("C");
}
Multiple choicemedium

Which condition is true on Saturday or Sunday?

Fix the bugmedium

The program should print Delivery included! when the basket is £40 or more, otherwise Add £X to get delivery included. It currently has two bugs. Fix them.

const basket = 32;

if (basket > 40); {
  console.log("Delivery included!");
} else {
  console.log(`Add £${40 - basket} to get delivery included`);
}
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Add £8 to get delivery included"
  • Does not log the included message
  • No errors

JavaScript if...else Quiz

3 questions to check what you learned.

  1. When does the else block run?

    • Always
    • When the first condition is true
    • Never
    • When all previous conditions are false
  2. How many blocks can run in one if/else if/else chain?

    • All whose conditions are true
    • Exactly two
    • At most one
    • Unlimited
  3. What does if ("0") { … } do?

    • Skips the block
    • Throws an error
    • Runs the block, because "0" is a non-empty string (truthy)
    • Converts "0" to false

JavaScript if...else Challenge

Grade calculator

Write an if/else if/else chain that sets grade from score:

  • 90 or more → "A"
  • 75 to 89 → "B"
  • 50 to 74 → "C"
  • below 50 → "Retake"

Then log Grade: B for the given score.

const score = 81;
let grade;
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Grade: B"
  • grade is "B"