The if statement in JavaScript is used to execute a block of code only if a specified condition is true. It is a fundamental control flow statement that allows you to perform different actions based on different conditions.

Basic Syntax

  if (condition) {
    // Code to execute if the condition is true
}
  

Example

  let age = 18;

if (age >= 18) {
    console.log("You are an adult.");
}
  

In this example, the message “You are an adult.” is logged to the console because the condition age >= 18 is true.

if-else Statement

The if-else statement allows you to execute one block of code if the condition is true and another block of code if the condition is false.

Syntax

  if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}
  

Example

  let age = 16;

if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are a minor.");
}
  

In this example, the message “You are a minor.” is logged to the console because the condition age >= 18 is false.

if-else if-else Statement

The if-else if-else statement allows you to test multiple conditions by chaining multiple else if statements. The first condition that evaluates to true will have its block of code executed.

Syntax

  if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition2 is true
} else {
    // Code to execute if none of the conditions are true
}
  

Example

  let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else if (score >= 60) {
    console.log("Grade: D");
} else {
    console.log("Grade: F");
}
  

In this example, the message “Grade: B” is logged to the console because the condition score >= 80 is true.

Nested if Statements

You can nest if statements within each other to create more complex conditions.

Example

  let age = 20;
let hasID = true;

if (age >= 18) {
    if (hasID) {
        console.log("You are allowed to enter.");
    } else {
        console.log("You need to show your ID.");
    }
} else {
    console.log("You are not allowed to enter.");
}
  

In this example, the message “You are allowed to enter.” is logged to the console because both conditions age >= 18 and hasID are true.