else: The Backup Plan

Grade 4, page 2 of 11. A one-minute read.

Often you want to do one thing if the condition is true, and something else if it's false. That's what else is for:

JavaScript
const age = 15;

if (age >= 18) {
  console.log("You can vote! 🗳️");
} else {
  console.log(`You can vote in ${18 - age} years.`);
}

It prints

You can vote in 3 years.

Think of it as a fork in the road. JavaScript will take exactly one of the two paths, never both, and never neither. If the condition is true, it runs the first block. Otherwise, it runs the else block.

JavaScript
const password = "open sesame";
const typedPassword = "open sesam";

if (typedPassword === password) {
  console.log("Welcome in! 🔓");
} else {
  console.log("Wrong password. Access denied! 🔒");
}

It prints

Wrong password. Access denied! 🔒

One missing letter, and you're locked out. Computers are very strict doormen.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning