JavaScript Nested If Else Statement

JavaScript Nested If Else Statements are created when inside an if-else statement, another if-else statement is found. This can be done more than one time and more than one if-else statements can be nested inside each other 🔗.

Note: Before you get to this part, make sure you know the basics of JavaScript If Else statement.

Syntax of JavaScript Nested If Else Statement: 😵

if (condition1) {
   // this block runs only when the condition1 given above is true
   if (condition2) {
      // this block runs only when condition1 is true and afterwards condition2 is also true    
   } else {
      // this block runs only when condition1 is true but condition2 is false
   }
} else {
   // this block runs only when the condition1 given above is false
}

Example:

if (true) {// 1st condition
  console.log('1st condition is true');
  if (true) {// 2nd condition
    console.log('2nd condition is also true');
  } else {
    console.log('1st condition is true but 2nd condition is false');
  }
} else {
  console.log('1st condition is false');
}

Output

1st condition is true
2nd condition is also true

Nested If Else Statement with conditional operators ➰

You can check out our JavaScript Operators lesson for more info on operators.

var age = 16;

if (age > 15) {
  console.log('Age is greater than 15. You must be a teenager.');
  if (age >= 18) {
    console.log('Eligible for driving.');
  } else {
    console.log('Teenager but not eligible for driving.');
  }
} else {
  console.log('Age is less than 15.');
}

Output

Age is greater than 15. You must be a teenager.
Teenager but not eligible for driving.

While we can use nested if-else statements, it’s not advised to nest a lot of if-else inside each other because it complicates your code 😵 and also the speed of your program might decrease.