Mastering if...else in JavaScript
🧠 What is if...else?
The if...else statement in JavaScript is used to execute one block of code if a condition is true, and another block if the condition is false. It’s an essential tool for making decisions in your code.
>>“Programming is about making decisions. if...else is how we express them.” 🔍
📌 Syntax
Basic if...else Syntax
if (condition) {
// runs if condition is true
} else {
// runs if condition is false
}🌐 Example
Simple if...else
const isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}🔁 Multiple Conditions with else if
You can check more than two conditions using else if blocks.
Using else if
const score = 45;
if (score >= 90) {
console.log("🏆 Excellent");
} else if (score >= 60) {
console.log("👍 Good");
} else {
console.log("📘 Needs improvement");
}⚠️ Truthy and Falsy Reminder
Note
Any expression in the if condition gets converted to a boolean.
Falsy values include: "", 0, null, undefined, NaN, and false.
Falsy values include: "", 0, null, undefined, NaN, and false.
🔀 Nested if...else
You can nest one if...else inside another for complex decision trees.
Nested Example
const user = {
isLoggedIn: true,
isPremium: false
};
if (user.isLoggedIn) {
if (user.isPremium) {
console.log("Welcome, Premium User!");
} else {
console.log("Welcome, Regular User!");
}
} else {
console.log("Please log in.");
}🎯 Ternary Operator Shortcut
For simple if...else expressions, the ternary operator is a cleaner alternative:
Ternary Operator
const age = 16;
const message = age >= 18 ? "Access granted" : "Access denied";
console.log(message);💡 Best Practices
- Use braces even for one-liners to avoid bugs 🔐
- Keep conditions simple and readable 🧼
- Use else if instead of nested if when possible for clarity 🧭
📚 Further Reading
>>“If you don’t make decisions in code, the program does nothing. Decide wisely.” 🧠