HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript if, else, and else if

In JavaScript, you can use the if, else, and else if statements to control the flow of your code based on different conditions.

if Statement

The if statement is used to execute a block of code if a specified condition is true.

Syntax

if (condition) {
    // code block to be executed if the condition is true
} 
              

Example

let x = 10;

if (x > 5) {
    console.log("x is greater than 5");
}

} 
              

else statement:

The else statement is used in conjunction with the if statement to execute a block of code if the specified condition in the if statement is false.

Syntax

if (condition) {
    // code block to be executed if the condition is true
} else {
    // code block to be executed if the condition is false
} 
 

Example

let x = 3;

if (x > 5) {
    console.log("x is greater than 5");
} else {
    console.log("x is not greater than 5");
}
  

else if statement

It executes a block of code if the preceding if condition(s) are false, but its own condition is true.

Syntax

if (condition1) {
    // code block to be executed if condition1 is true
} else if (condition2) {
    // code block to be executed if condition1 is false and condition2 is true
} else {
    // code block to be executed if both condition1 and condition2 are false
} 
 

Example

let x = 3;

if (x > 5) {
    console.log("x is greater than 5");
} else if (x === 5) {
    console.log("x is equal to 5");
} else {
    console.log("x is less than 5");
}