If, Else If, and Else Statements
Every program needs to make decisions.
For example:
If age is above 18 ? allow login
If marks are high ? show “Pass”
If the item is out of stock ? show error
If username is empty ? show warning
JavaScript uses if, else if, and else statements to perform these decisions.
This chapter will help you understand how to use them confidently.
What Is an if Statement?
An if statement checks a condition.
If the condition is true, the code inside runs.
Syntax:
if (condition) {
// code to run when condition is true
}
Example 1: Simple if Statement
let age = 20;
if (age >= 18) {
console.log("You are eligible.");
}
Output:
You are eligible.
What Is an else Statement?
The else block runs when the if condition is false.
Example:
let marks = 30;
if (marks >= 35) {
console.log("Pass");
} else {
console.log("Fail");
}
Output:
Fail
What is else if?
Use else if when you have multiple conditions to check.
Example:
let score = 75;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else if (score >= 60) {
console.log("Grade C");
} else {
console.log("Grade D");
}
Output:
Grade B
Example: Checking Temperature
let temp = 15;
if (temp > 30) {
console.log("Hot");
} else if (temp > 20) {
console.log("Warm");
} else {
console.log("Cold");
}
Output:
Cold
Multiple Conditions Using && and ||
Example with AND (&&)
let age = 19;
let id = true;
if (age >= 18 && id) {
console.log("Entry allowed");
}
Output:
Entry allowed
Example with OR (||)
let day = "Sunday";
if (day === "Saturday" || day === "Sunday") {
console.log("Weekend");
}
Output:
Weekend
Nested if Statements (if inside if)
let username = "aman";
let password = "1234";
if (username === "aman") {
if (password === "1234") {
console.log("Login successful");
} else {
console.log("Wrong password");
}
} else {
console.log("User not found");
}
Output:
Login successful
Real-Life Example: Shopping Discount
let amount = 1200;
if (amount >= 2000) {
console.log("Discount: 20%");
} else if (amount >= 1000) {
console.log("Discount: 10%");
} else {
console.log("No discount");
}
Output:
Discount: 10%
Real-Life Example: Eligibility Check
let age = 17;
if (age >= 18) {
console.log("Eligible for voting");
} else {
console.log("Not eligible");
}
Example Program (Complete Decision Tree)
let marks = 82;
if (marks >= 90) {
console.log("Excellent");
} else if (marks >= 75) {
console.log("Very Good");
} else if (marks >= 50) {
console.log("Good");
} else if (marks >= 35) {
console.log("Pass");
} else {
console.log("Fail");
}
Output:
Very Good
Common Mistakes Beginners Make
Using
=instead of==or===Missing curly braces
{}for multiple statementsWriting else if without else
Wrong ordering of conditions
Confusing logical operators