JavaScript if, else and else if
Last Updated : 15 Apr, 2025
In JavaScript, conditional statements allow you to make decisions in your code. The if, else, and else if statements are used to control the flow of execution based on certain conditions.
The if statement
The if statement executes a block of code if a specified condition evaluates to true. If the condition is false, the code inside the if block is skipped.
Syntax
if (condition) {
// Code to execute if condition is true
}
JavaScript let age = 20; if (age >= 18) { console.log("You are an adult."); }
In this example, if the value of age is greater than or equal to 18, the message "You are an adult." will be printed to the console.
The if else statement
The else statement follows an if statement and provides an alternative block of code to run when the condition in the if statement is false. It is used for creating conditional logic that handles both cases (true and false).
Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
JavaScript let age = 16; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are a minor."); }
In this case, since the value of age is 16 (which is less than 18), the message "You are a minor." will be printed.
The else if statement
The else if statement allows you to check multiple conditions sequentially. It can be used when you want to test more than one condition and handle each case with a different block of code. You can chain multiple else if statements after the initial if and before the final else.
Syntax:
if (condition1){
// Code to execute if expression1 turns to true
}
else if (condition2){
// Code to execute if expression2 turns to true
}
else{
// Code to execute if none of the expressions turns to true
}
JavaScript let temp = 30; if (temp >= 30) { console.log("It's hot outside."); } else if (temp >= 20) { console.log("It's warm outside."); } else if (temp >= 10) { console.log("It's cool outside."); } else { console.log("It's cold outside."); }