The if Statement in JavaScript
🧠 What is the if Statement?
The if statement is a fundamental control structure in JavaScript that allows code to be executed conditionally based on whether an expression evaluates to true or false. It's the basic building block for decision-making in programs.
>>“Code is not just instructions — it’s decisions. And if leads the way.” 🧭
🔧 Syntax
Basic if Syntax
if (condition) {
// code to run if condition is true
}🌐 Example
Simple if Statement
const temperature = 25;
if (temperature > 20) {
console.log("It's a warm day! ☀️");
}➕ Adding else and else if
You can enhance the if statement using else and else if for multiple decision branches.
if, else if, else
const score = 85;
if (score >= 90) {
console.log("🏅 Excellent!");
} else if (score >= 75) {
console.log("🎉 Good job!");
} else {
console.log("📚 Keep practicing!");
}⚠️ Truthy & Falsy Values
Note
JavaScript automatically converts values in if conditions to boolean.
Falsy values include: false, 0, "", null, undefined, and NaN.
Falsy values include: false, 0, "", null, undefined, and NaN.
Falsy Check
const name = "";
if (!name) {
console.log("Name is empty");
}🧪 Nested if Statements
You can nest if statements for more complex logic:
Nested if Example
const user = {
loggedIn: true,
isAdmin: true
};
if (user.loggedIn) {
if (user.isAdmin) {
console.log("Welcome, admin!");
}
}📌 Ternary Alternative
For simple if-else checks, you can use a ternary operator:
Ternary Operator
const age = 18;
const access = age >= 18 ? "Granted" : "Denied";
console.log(access); // "Granted"💡 Best Practices
- Use curly braces even for single-line blocks to avoid bugs
- Don’t nest too deeply — extract logic into functions
- Keep conditions readable and meaningful
📚 Further Reading
>>“Decisions shape programs just as choices shape lives. Use if wisely.” 🧘♂️