else if statement

The else if statement is used in the cases where you need to execute multiple code blocks based on multiple conditional expression. It starts with the if statement and ends with the else statement, it is written in between them.

Syntax:

if (conditional_expression1){
// Code to execute if expression1 turns to true
}
else if (conditional_expression2){
// Code to execute if expression2 turns to true
}
else{
// Code to execute if none of the expressions turns to true
}

Example: The below code will explain the practical use of the else if statement in JavaScript.

Javascript
const num1 = 45;
const num2 = 8;

if(num1 < 50){
    console.log(`${num1} is less than 50`);
}
else if(num1 === 50){
    console.log(`${num1} is equal to 50`);
}
else{
    console.log(`${num1} is greater than 50`);
}

if(num1+num2 === 50){
    console.log
    (`The sum of numbers ${num1} and ${num2} is equal to 50.`);
}
else if(num1+num2 > 50){
    console.log
    (`The sum of numbers ${num1} and ${num2} is greater than 50.`);
}
else{
    console.log
    (`The sum of numbers ${num1} and ${num2} is less than 50.`);
}

if(num1-num2 > 50){
    console.log
    (`The difference of numbers ${num1} and ${num2} is greater than 50.`);
}
else if(num1-num2 === 50){
    console.log
    (`The difference of numbers ${num1} and ${num2} is equal to 50.`);
}
else{
    console.log
    (`The difference of numbers ${num1} and ${num2} is less than 50.`);
}

Output
45 is less than 50
The sum of numbers 45 and 8 is greater than 50.
The difference of numbers 45 and 8 is less than 50.


JavaScript if else else if

The if…else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed. This structure facilitates decision-making in JavaScript programs.

We have the following conditional statements available in JavaScript:

Table of Content

  • if statement
  • if else statement
  • else if statement

Similar Reads

if statement

The if statement is defined using the if keyword and is always operated with an expression passed inside the round brackets just after its definition....

if else statement

The if else statement is an extended version of the if condition. It allows you to write code for both the cases i.e. either the expression returns true or false, you can handle both of them. The if statement will run for the true value while else for the false value....

else if statement

The else if statement is used in the cases where you need to execute multiple code blocks based on multiple conditional expression. It starts with the if statement and ends with the else statement, it is written in between them....

Contact Us