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.
JavaScript if else statement – Interview Questions
Q 1: What is an if statement?
Q 2: What is an else statement?
Q 3: What is else-if?
Q 4: Can if statements be nested?
Q 5: What data type does if condition expect?
JavaScript if else statement – Objective Questions (MCQs)
Q1. Which keyword is used to execute code when a condition is true?
Q2. Which statement executes when the if condition is false?
Q3. What will be the output of: if (5 > 3) { console.log("Yes"); }
Q4. Which statement is used to check multiple conditions?
Q5. The if else statement is an example of ______ control structure.