JavaScript if, else and else if: Conditionals, Braces, Guard Clauses and Common Mistakes
How if, else and else if decide what runs, how truthiness affects conditions, the dangling-else trap and why braces matter, why else if is just nesting, guard clauses and early returns for flatter code, writing clear conditions, and the classic mistakes: = instead of ===, empty arrays and NaN.
kvi5hnuCode Sprout team member7 min readOn this page
if is the most basic way to make a program decide: run this code only when some condition holds. Every language has it, and JavaScript's version looks like C's and Java's. Its JavaScript-specific details come from truthiness (article 17) and from optional braces, which together cause most if-related bugs.
The if statement
if (condition) statement
if (condition) statement else otherStatement
The condition is any expression, and the parentheses around it are required. JavaScript evaluates it and converts the result to a boolean: if it's truthy, the statement runs; if it's falsy, the else statement runs (when there is one).
function describeStock(count) {
if (count === 0) {
return "Out of stock";
} else {
return `${count} left`;
}
}
console.log(describeStock(0), "|", describeStock(3));
Out of stock | 3 left
The syntax allows a single statement after if (...) and after else. A block { ... } counts as one statement, which is how you run several statements.
Conditions use truthiness, not true/false
The condition doesn't have to be a boolean. Any value works, and it's tested for truthiness. That's convenient, but it means you must know which values are falsy: false, 0, -0, 0n, "", null, undefined and NaN.
for (const value of [0, "", "0", [], null, NaN, " "]) {
if (value) {
console.log(JSON.stringify(value), "is truthy");
}
}
"0" is truthy
[] is truthy
" " is truthy
Two consequences you'll meet constantly:
if (count)is false for a count of 0, andif (name)is false for an empty string. When 0 or""is a valid value, test explicitly:if (count !== undefined),if (name !== "").- An empty array or object is truthy.
if (results)is true for[]. To ask "are there any results?", testif (results.length > 0).
A useful idiom: if (value == null) is true for both null and undefined and nothing else. It's the one place where many style guides allow == (article 23). The modern alternative is to handle missing values with ?? or ?. instead of a branch.
Always use braces
When the body is a single statement, braces are optional:
if (isAdmin) showAdminPanel();
It's tempting, and it causes two well-known bugs. The first: adding a second line that looks like it's inside the if but isn't:
if (isAdmin)
showAdminPanel();
logAccess(); // always runs: only the first line belongs to the if
The second is the dangling else. With nested ifs and no braces, an else always belongs to the nearest if that doesn't have one, whatever the indentation says:

const loggedIn = true, isAdmin = false;
if (loggedIn)
if (isAdmin)
console.log("admin panel");
else
console.log("login form"); // looks like the outer else, but isn't
login form
A logged-in user sees the login form, and a logged-out user would see nothing. With braces, the structure is explicit and the bug can't happen:
if (loggedIn) {
if (isAdmin) {
showAdminPanel();
}
} else {
showLoginForm();
}
Most style guides require braces for all multi-line bodies (ESLint's curly rule), and formatters such as Prettier fix the indentation so it always matches the real structure. A single-line if (done) return; without braces is widely accepted.
else if chains
To choose between more than two paths, chain conditions with else if:
function classify(n) {
if (n < 0) {
return "negative";
} else if (n === 0) {
return "zero";
} else if (n < 10) {
return "small";
} else {
return "large";
}
}
console.log([-3, 0, 4, 99].map(classify).join(" "));
negative zero small large
else if isn't a separate keyword. It's an else whose single statement happens to be another if. The chain above is exactly the same as nesting each if inside the previous else, just formatted flat. Conditions are tested in order, and only the first matching branch runs, so put the more specific conditions first: if n < 10 came before n === 0, zero would be classified as "small".
When every branch compares the same value against constants, a switch or a lookup object can be clearer (article 40).
Guard clauses and early returns
Deeply nested ifs are hard to follow: the reader has to keep every enclosing condition in mind. A common refactoring is to handle the special cases first and return early, so the main logic isn't nested at all:
// Nested: the real work is three levels deep
function shippingCost(order) {
if (order) {
if (order.items.length > 0) {
if (order.total < 50) {
return 4.99;
} else {
return 0;
}
}
}
return 0;
}
function shippingCost(order) {
if (!order || order.items.length === 0) return 0; // nothing to ship
if (order.total >= 50) return 0; // free shipping
return 4.99; // the normal case
}
console.log(shippingCost(null), shippingCost({ items: [1], total: 80 }), shippingCost({ items: [1], total: 20 }));
0 0 4.99
Each guard clause deals with one case and exits. What remains at the bottom is the normal path. Guard clauses also make else unnecessary after a return, which ESLint's no-else-return rule can enforce.
Writing clear conditions
A few habits make conditions easier to read and review:
- Name complex conditions.
const canCheckout = cart.items.length > 0 && user.verified && !store.closed; if (canCheckout) {...}reads like a sentence and documents intent. - Avoid double negatives.
if (!isNotValid)makes readers stop. Rename the variable (isValid), or use De Morgan's laws to remove a wrapping!(article 34). - Prefer positive conditions in
if/else.if (isValid) { save() } else { warn() }reads better thanif (!isValid) { warn() } else { save() }. - Use the conditional operator for values.
const label = count === 1 ? "item" : "items";instead of anifthat assigns aletin two branches (article 37). - Use optional chaining in conditions.
if (user?.settings?.darkMode)replacesif (user && user.settings && user.settings.darkMode).
Common mistakes
let attempts = 0;
if (attempts = 3) { // assignment, not comparison: always truthy
console.log("assigned! attempts is now", attempts);
}
const ratio = 0 / 0;
if (ratio === NaN) {
console.log("never printed");
} else {
console.log("NaN is not equal to itself; use Number.isNaN");
}
const list = [];
if (list) console.log("an empty array is truthy");
if (list.length === 0) console.log("this is how to test for empty");
assigned! attempts is now 3
NaN is not equal to itself; use Number.isNaN
an empty array is truthy
this is how to test for empty
=instead of===. The assignment's value is used as the condition. ESLint'sno-cond-assign(in the recommended set) catches it.- Comparing with
NaN. Nothing equalsNaN, not evenNaN(article 11). UseNumber.isNaN(x). - Testing objects for emptiness by truthiness. Use
.lengthfor arrays and strings,.sizefor Maps and Sets,Object.keys(obj).lengthfor plain objects. - A semicolon after the condition:
if (x > 0);makes the empty statement the body (article 38).
Common questions
Is there an elif or elsif keyword in JavaScript?
No. else if is two keywords: an else whose statement is an if. It behaves exactly like the dedicated keywords in other languages.
Should I write if (isReady === true)?
Only if isReady might hold other truthy values that you need to exclude. For a real boolean, if (isReady) is equivalent and clearer. Comparing with true is a common sign of uncertainty about the variable's type; TypeScript removes that uncertainty (part 17).
if/else, the ternary operator, or && for conditional code?
if for actions, especially multi-line ones. The ternary operator for choosing between two values. && for a value that exists only when a condition holds, such as in JSX, as long as the left side is a real boolean (article 34).
Does the order of conditions in if (a && b) matter?
For correctness, it can: b isn't evaluated when a is falsy, so put the safety check first, as in if (user && user.isActive). For speed, putting a cheap, usually-false check first saves evaluating an expensive one.
Summary
if (condition)runs its statement when the condition is truthy;elseruns otherwise. The parentheses are required.- Remember the falsy values:
0,""andNaNare falsy;"0",[]and{}are truthy. - Without braces, only one statement belongs to the
if, and anelsepairs with the nearestif. Always use braces for bodies. else ifis anelsecontaining anif; branches are tested in order and the first match wins.- Use guard clauses and early returns to keep the main path unnested.
- Watch for
=in conditions, comparisons withNaN, and truthiness tests on empty arrays.
Practice Questions
What does this code print?
if ("false") console.log("yes");
else console.log("no");
Answer
yes. "false" is a non-empty string, and every non-empty string is truthy.
A function should greet with the user's name, or "guest" when the name is missing. Why is this code not quite right if user might be null, and how do you fix it?
if (user.name) {
...
} else {
...
}
Answer
If user is null, reading user.name throws a TypeError before the condition is tested. Use optional chaining: if (user?.name). (An empty-string name also goes to the guest branch, which is probably fine here.)
Rewrite with guard clauses:
function f(x) {
if (x !== null) {
if (x > 0) {
return Math.sqrt(x);
}
}
return 0;
}
Answer
function f(x) {
if (x === null || x <= 0) return 0;
return Math.sqrt(x);
}
One guard handles both special cases, and the main calculation isn't nested.
Order these conditions correctly for a grading function: score >= 70, score >= 90, score >= 80.
Answer
score >= 90 first, then score >= 80, then score >= 70. Branches are tested in order and the first match wins, so the most demanding condition must come first; otherwise a 95 would match score >= 70 and get the lowest grade.
Previous: JavaScript Statements: Expression Statements, Blocks, Empty Statements and Declarations
Next: JavaScript switch Statement: case Matching, Fall-Through, default and Alternatives

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.