← 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
Ready to go further?

These free tutorials are a preview, our Frontend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Frontend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account