JavaScript if/else & Truthy/Falsy
Conditionals let your code make decisions based on different situations.
if Statement
Checks a condition and runs code only if it’s true:
let temperature = 30;
if (temperature > 25) {
console.log("It's hot outside!");
}
else Statement
Provides an alternative when the condition is false:
let temperature = 15;
if (temperature > 25) {
console.log("It's hot!");
} else {
console.log("It's cool!");
}
else if — Multiple Conditions
let score = 85;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
JavaScript checks conditions in order. It runs the first true block and skips the rest.
Truthy and Falsy Values
JavaScript treats non-boolean values as true or false:
// Falsy — treated as false
false, 0, "", null, undefined, NaN
// Truthy — treated as true
true, 1, -1, "hello", " ", [], {}, function(){}
Remember: An empty array [] is truthy, even though it has no elements.
let name = "John";
// Direct truthy check — cleaner
if (name) {
console.log("Name exists");
}
Ternary Operator
Short if/else for simple conditions:
let age = 18;
let status = age >= 18 ? "Adult" : "Minor";
Format: condition ? valueIfTrue : valueIfFalse
Complete Example: Login Check
let username = null;
let isLoggedIn = false;
let isAdmin = false;
if (!username) {
console.log("Please log in");
} else if (!isLoggedIn) {
console.log("Account not active");
} else if (isAdmin) {
console.log("Welcome, Admin!");
} else {
console.log("Welcome, User!");
}
Best Practices
- Use strict equality —
===prevents type coercion bugs - Use early returns — Reduce nesting
- Keep conditions simple — Break complex logic apart
- Use ternary for simple cases — Don’t overcomplicate
- Understand truthy/falsy — Prevents unexpected behavior
Common Mistakes
- Using
==instead of===— Type coercion causes bugs - Forgetting
else— No fallback case - Deep nesting — Hard to read and maintain
- Confusing truthy/falsy —
0and""are falsy - Assignment in condition — Use
===not=