if in JavaScript
The if statement executes a block of code only when a condition evaluates to a truthy value. It is the most fundamental control flow construct in JavaScript and appears in nearly every program.
Truthy and Falsy Values
Before using if, understand what JavaScript considers false in a condition:
| Falsy | Everything else is truthy |
|---|---|
false, 0, -0, 0n |
"hello", 1, -1, [], {} |
"" (empty string) |
"0", "false" (non-empty strings) |
null, undefined, NaN |
Functions, objects, arrays |
if ("0") {
console.log("Runs — non-empty string is truthy");
}
Basic if Statement
if (condition) {
// Runs when condition is truthy
}
Example
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
if-else Statement
Execute one block when true, another when false:
let temperature = 35;
if (temperature > 30) {
console.log("It's hot outside.");
} else {
console.log("Enjoy the weather.");
}
if-else if-else Chain
Test multiple conditions in order — the first true branch runs, then the chain stops:
let score = 85;
let grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
console.log(`Grade: ${grade}`); // Grade: B
Order matters — check highest thresholds first.
Logical Operators in Conditions
Combine conditions with && (AND), || (OR), and ! (NOT):
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive.");
}
if (age < 13 || age > 65) {
console.log("Eligible for discount.");
}
if (!hasLicense) {
console.log("License required.");
}
Ternary Operator (Conditional Expression)
For simple assignments, the ternary operator is more concise:
let status = age >= 18 ? "adult" : "minor";
// Equivalent if-else:
let status2;
if (age >= 18) {
status2 = "adult";
} else {
status2 = "minor";
}
Avoid nesting ternaries deeply — they become unreadable.
Nested if Statements
Nest if blocks for compound logic:
let age = 20;
let hasID = true;
let isVIP = false;
if (age >= 18) {
if (hasID) {
if (isVIP) {
console.log("VIP lounge access.");
} else {
console.log("General admission.");
}
} else {
console.log("Please show your ID.");
}
} else {
console.log("Must be 18 or older.");
}
Refactor deeply nested if statements into guard clauses or early returns:
function checkAccess(age, hasID, isVIP) {
if (age < 18) return "Must be 18 or older.";
if (!hasID) return "Please show your ID.";
if (isVIP) return "VIP lounge access.";
return "General admission.";
}
Nullish Coalescing and Optional Chaining
Modern alternatives to verbose null checks:
// Old style
let name;
if (user !== null && user !== undefined) {
name = user.name;
} else {
name = "Guest";
}
// Modern
let name2 = user?.name ?? "Guest";
Best Practices
- Prefer early returns over deep nesting in functions.
- Use strict equality (
===) in conditions — avoid type coercion surprises with==. - Keep conditions readable — extract complex logic into named variables or functions.
- Always include an
elsefor exhaustive handling when every case must produce a result. - Don’t assign inside conditions unless intentional:
if (x = getValue())is usually a bug.
Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
if (x = 5) |
Assignment, not comparison | Use if (x === 5) |
Checking array.length with truthy |
[].length is 0 (falsy) but array exists |
Use array.length > 0 or array.length === 0 |
| Missing braces on multi-line blocks | Only first line is conditional | Always use { } blocks |
| Duplicate conditions in chain | Dead code never runs | Reorder or remove duplicates |
Troubleshooting
- Condition always true/false — Log the variable:
console.log(typeof x, x)before theif. - Unexpected branch taken — Check for type coercion; use
===and explicit comparisons. - Code after
ifruns unexpectedly — Verify braces scope; a missing{causes only the next statement to be conditional.
The if statement is simple on the surface but mastering truthy/falsy evaluation, guard clauses, and readable condition structure separates beginner code from professional JavaScript.