Conditionals: if / else if / else

A free sample lesson from JavaScript Basics

The idea

A fork in a path with a true/false sign at each branch - walk down the first branch whose sign says true, skip the rest.

What it actually is

if/else if/else lets your program choose between different paths depending on whether a condition is true or false - checked top to bottom, first match wins.

How you write it

if (condition) {
  ...
} else if (condition) {
  ...
} else {
  ...
}

A worked example

let score = 85;
if (score >= 90) {
  console.log("A");
} else if (score >= 70) {
  console.log("B");
} else {
  console.log("C");
}

score is 85. The first check (>= 90) is false, so JavaScript moves to the next: (>= 70) is true, so "B" prints and nothing else runs - the rest of the chain is skipped once a match is found.

let temperature = 45;
if (temperature < 32) {
  console.log("Freezing!");
} else if (temperature < 60) {
  console.log("Chilly");
} else {
  console.log("Warm");
}

45 isn't below 32, but it IS below 60, so "Chilly" prints. Order matters - JavaScript always checks from the top down.

Mistakes children actually make

Mistake 1: writing if (score = 90) with a single = instead of === - this doesn't compare, it ASSIGNS 90 to score and the condition is always true! Always use === to compare, = to store. Mistake 2: forgetting the curly braces { } around a multi-line block - JavaScript only treats the very next line as part of the if, so later lines can run even when they shouldn't. Mistake 3: ordering checks from broadest to narrowest - if (score >= 70) { ... } else if (score >= 90) { ... } means the >= 90 branch can NEVER run, because any score of 90+ already matched the first, broader check; put the most specific conditions first.

Then they try it

In the app this lesson continues with the animated explanation, spoken aloud, and then the practice: If lives > 0, print "Still playing!" - otherwise print "Game over!" The editor runs your child’s real code and checks the result, with their coding buddy reacting to what they wrote.

Try it free