JavaScript if, else, and else if
8 April 2025 | Category: JavaScript
The if
, else
, and else if
statements are used to perform conditional logic in JavaScript. They allow your code to make decisions based on different conditions.
✅ Basic if
Statement
The if
statement runs a block of code only if a specified condition is true.
if (condition) {
// Code to run if condition is true
}
Example:
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
Output:
You are an adult.
🔁 if...else
Statement
Use else
to run a block of code if the condition is false.
if (condition) {
// Run this if true
} else {
// Run this if false
}
Example:
let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
Output:
Please log in.
🔄 if...else if...else
Statement
When you need to check multiple conditions, use else if
.
if (condition1) {
// Run if condition1 is true
} else if (condition2) {
// Run if condition2 is true
} else {
// Run if none are true
}
Example:
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else {
console.log("Grade: C or below");
}
Output:
Grade: B
🧪 Nested if Statements
You can place if
statements inside other if
blocks.
let user = "admin";
let loggedIn = true;
if (loggedIn) {
if (user === "admin") {
console.log("Welcome, Admin!");
}
}
🔐 Practical Example: Login Check
let username = "john";
let password = "12345";
if (username === "john" && password === "12345") {
console.log("Login successful!");
} else {
console.log("Invalid credentials.");
}
📌 Summary
- Use
if
to run code when a condition is true. - Use
else
to handle the false case. - Use
else if
to test multiple conditions. - You can nest
if
statements for more complex logic.