Codiqo

Learn JavaScript · lesson 14 of 60 · about 8 minutes

else if and Nested Conditions

Greet visitors by the time of day: choose between several options with else if, and put decisions inside decisions.

What you'll learn

  • Chain conditions with else if
  • Order conditions correctly
  • Nest an if inside another

Morning, afternoon or evening?

Sam wants to greet visitors by the time of day: good morning, good afternoon or good evening. That's three choices, and if with else only gives you two.

More than two paths

else if adds extra conditions. JavaScript checks from the top and runs only the first branch that's true, then skips the rest.

Weather advice

const temp = 12;
if (temp > 25) {
  console.log("Shorts");
} else if (temp > 10) {
  console.log("Jumper");
} else {
  console.log("Coat");
}

Output

Jumper

Order matters

Because only the first true branch runs, check in one direction. hour < 12 has to come before hour < 18: if the 18 check came first, every morning hour would match it, and nobody would ever be wished good morning.

A greeting for the time of day

const hour = 15;
let hello;
if (hour < 12) {
  hello = "Good morning";
} else if (hour < 18) {
  hello = "Good afternoon";
} else {
  hello = "Good evening";
}
document.querySelector("#time").textContent = `${hello}, Ada!`;

Decisions inside decisions

You can put an if inside another if. The inner one is only checked when the outer one is true.

Nested checks

const loggedIn = true;
const isPlus = false;
if (loggedIn) {
  if (isPlus) {
    console.log("Unlimited fuel");
  } else {
    console.log("Fuel: 5");
  }
} else {
  console.log("Please sign in");
}

Output

Fuel: 5

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.