In JavaScript, if, else
, and else if
are control flow statements that allow you to execute certain blocks of code based on specific conditions. These statements help you make decisions in your code.
1. if Statement
The if
statement is used to execute a block of code if a specified condition is true.
Syntax:
if (condition) {
// Code to execute if the condition is true
}
Example:
let age = 21;
if (age >= 21) {
console.log("Age of boy adult.");
}
In this example, the message “Age of boy adult.” will be logged to the console because the condition age >= 21
is true.
2. else Statement
The else
statement is used to execute a block of code if the if
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 = 20;
if (age >= 21) {
console.log("You are an adult.");
} else {
console.log("You are not an adult.");
}
In this example, the message “You are not an adult.” will be logged to the console because the condition age >=
21 is false.
else if Statement
The else if
statement allows you to check additional conditions if the previous if
condition is false. You can chain multiple else if
statements together.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if both condition1 and condition2 are false
}
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 {
console.log("Grade: F");
}
In this example, the message Grade: B will be logged to the console because the condition score >= 80
is true, and the conditions before it are false.