← JavaScript tutorial

JavaScript

Conditionals (if / else)

if runs a block only when its condition is true. Add else if for another condition to check if the first was false, and a final else to catch everything else.

Example: a greeting that depends on the time of day

const hour = 14;
let greeting;

if (hour < 12) {
  greeting = "Good morning";
} else if (hour < 18) {
  greeting = "Good afternoon";
} else {
  greeting = "Good evening";
}

document.getElementById("output").textContent = greeting;

JavaScript checks each condition top to bottom and stops at the first one that's true — so even though hour < 18 would also be true for an hour of 9, it never gets checked because hour < 12 already matched first. Order matters: put your most specific conditions before more general ones that would also match.

Try it yourself