0
0
JavascriptHow-ToBeginner · 3 min read

How to Write Nested If Else in JavaScript: Simple Guide

In JavaScript, you write nested if else statements by placing one if else block inside another. This lets you check multiple conditions step-by-step, like asking questions inside questions.
📐

Syntax

A nested if else means putting one if else inside another. The outer if checks the first condition. If it’s true, it runs its code. If false, the else can have another if else to check more conditions.

Structure:

if (condition1) {
  // code if condition1 is true
} else {
  if (condition2) {
    // code if condition2 is true
  } else {
    // code if both conditions are false
  }
}
javascript
if (condition1) {
  // code if condition1 is true
} else {
  if (condition2) {
    // code if condition2 is true
  } else {
    // code if both conditions are false
  }
}
💻

Example

This example checks a number and prints if it is positive, negative, or zero using nested if else statements.

javascript
const number = 5;

if (number > 0) {
  console.log('The number is positive');
} else {
  if (number < 0) {
    console.log('The number is negative');
  } else {
    console.log('The number is zero');
  }
}
Output
The number is positive
⚠️

Common Pitfalls

One common mistake is forgetting to use braces {} which can cause unexpected behavior. Another is confusing the nesting levels, making the code hard to read or causing logic errors.

Wrong example (missing braces):

if (x > 0)
  if (x < 10)
    console.log('x is between 1 and 9');
  else
    console.log('x is zero or negative');

This code runs else only for the inner if, not the outer one, which is usually not what you want.

Right example (with braces):

if (x > 0) {
  if (x < 10) {
    console.log('x is between 1 and 9');
  }
} else {
  console.log('x is zero or negative');
}
javascript
if (x > 0)
  if (x < 10)
    console.log('x is between 1 and 9');
  else
    console.log('x is zero or negative');

// Corrected version
if (x > 0) {
  if (x < 10) {
    console.log('x is between 1 and 9');
  }
} else {
  console.log('x is zero or negative');
}
📊

Quick Reference

  • Use braces {} to clearly define blocks.
  • Indent nested blocks for readability.
  • Test each condition carefully to avoid logic errors.
  • Consider else if for cleaner multiple conditions.

Key Takeaways

Nested if else lets you check multiple conditions step-by-step inside each other.
Always use braces {} to avoid confusion and bugs in nested blocks.
Indent your code to make nested conditions easy to read.
Use else if for simpler multiple condition checks when possible.
Test your logic carefully to ensure conditions work as expected.