Else if

Open the project folder

In our starter files, open the index.html page from this lessons folder:

06.Loops-and-conditionals > 05.Else if

Starter example

Using this same example as the previous lesson, here we are handling two conditions at the top level. We check if a user is logged in or logged out:

let user = { name: 'Chris', role: 'subscriber' };
if (user) {
  console.log('user logged in...');
  if (user.role === 'admin') {
    console.log('hey admin!');
  } else {
    console.log('hey user!');
  }
} else {
  console.log('user logged out');
}

We also have a nested if...else too, which provides two further options if the user object is present. But what if we want three top-level options?

Issues with multiple if statements

For this we have else if. Let’s just simplify this by removing the nested statements:

if (user) {
  console.log('user logged in...');
} else {
  console.log('user logged out');
}

Previously, we looked at a way to handle three conditions by adding more than one if statement:

if (user) {
  console.log('user logged in...');
}
if() {}
else {
  console.log('user logged out');
}

But the problem we have is that the else section will only apply to the last if section, the first if section here is disconnected.

Using else if

If we want to do this and keep all three connected, we turn this into else if:

let user = { name: "Chris", role: "subscriber" };

if (user) {
  console.log('user logged in...');
}
else if (user && user.role === 'subscriber') {
  console.log('else if section ran');
}
else {
  console.log('user logged out');
}

This else if will not currently run because the first if condition is met, causing it to not go any further.

So, we can be more specific with the first check:

let user = { name: "Chris", role: "subscriber" };

// also checks if the user is an admin
if (user && user.role === "admin") {
  console.log("user logged in...");
} else if (user && user.role === "subscriber") {
  console.log("else if section ran");
} else {
  console.log("user logged out");
}

This will cause the else if section to run. We can do whatever we want in each of these sections, we can show and hide content depending on the user’s role, we can redirect to an account area, we can disable features which the user may not be allowed to access and anything else you can think of.

We can also use multiple else if sections too:

// 1. change role to author
let user = { name: 'Chris', role: 'author' };

if (user && user.role === 'admin') {
  console.log('user logged in...');
}
else if (user && user.role === 'subscriber') {
  console.log('else if section ran');
}
// 2. add second else if
else if (user && user.role === 'author') {
  console.log('author');
}
else {
  console.log('user logged out');
}

This allows us to be more specific with the code to run for individual roles. Finally, if none of these if or else if sections are true, the else section will run.