Conditionals
Conditionals choose which code runs by testing a value. JavaScript treats many values as true or false, then takes the matching if, else if, or ternary branch.
Detailed Explanation
A conditional is a decision. You have a value, you ask whether it is truthy, and you run one path or another. The everyday form is if / else if / else. The compact form is the ternary operator condition ? whenTrue : whenFalse, which is an expression and therefore produces a value.
The decision is not a boolean check unless you write one. JavaScript first converts the condition with ToBoolean. These values are falsy: false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy, including "0", "false", [], {}, and new Boolean(false). That last one is an object, and objects are always truthy.
This is why if (count) is a different question from if (count === 0) or if (count != null). The first asks "is this a non-zero number?", which also rejects NaN. The second asks "is this exactly zero?". The third asks "is this neither null nor undefined?". Pick the question you mean.
else if is just an else whose body is another if. Only one branch runs. Order matters when conditions overlap: put the more specific test first. An empty if body with a following statement that looks indented is a real bug; JavaScript does not care about indentation.
The ternary is useful when you need a value, not a statement: const label = n === 1 ? "item" : "items". Nesting ternaries is legal and usually a mistake. Once you need a third outcome, write if / else or a switch.
Logical operators also act as conditionals. a && b returns a if a is falsy, otherwise b. a || b returns a if a is truthy, otherwise b. a ?? b returns a unless a is null or undefined. These are expressions, so they are common in assignments and JSX, and they short-circuit: the right side is not evaluated if the left side already decides the result.
Reach for an if when the branches do work. Reach for a ternary or ?? when you need a single value. Reach for switch when one value is compared against a list of constants.
What it costs you: accidental truthiness. if (items.length) is fine. if (items) is always true for an array, even an empty one. if (user.age) skips newborns. Be explicit when zero, empty string, or NaN are valid data.
Code Examples
const cart = { itemCount: 0, coupon: "" };
// Truthiness treats 0 as false, so this branch is wrong for a valid empty cart.
if (cart.itemCount) {
console.log("has items");
} else {
console.log("empty or missing"); // this runs
}
// Ask the question you mean.
if (cart.itemCount > 0) {
console.log("has items");
} else {
console.log("empty"); // => empty
}
// ?? only replaces null and undefined, so an empty coupon stays empty.
const coupon = cart.coupon ?? "NONE";
console.log(coupon); // => "" (empty string is not nullish)
const label = cart.itemCount === 1 ? "item" : "items";
console.log(`${cart.itemCount} ${label}`); // => 0 itemsfunction statusText(user) {
if (user == null) return "signed out";
if (user.role === "admin") return "admin";
if (user.role === "member") return "member";
return "guest";
}
console.log(statusText(null)); // => signed out
console.log(statusText({ role: "admin" })); // => admin
// && / || return operands, not booleans.
console.log("" || "fallback"); // => fallback
console.log("saved" || "fallback"); // => savedCommon Gotchas
Objects are always truthy
`if ([])` and `if ({})` both run. Test `array.length` or `Object.keys(obj).length` when emptiness is what you care about.
`== null` is the rare useful loose check
it is true for both `null` and `undefined`, and false for `0` and `""`. Anywhere else, prefer `===`.
A semicolon after `if` empties the branch
`if (ready); { start(); }` always calls `start`. The braces belong to a separate block.
Ternaries are expressions
you can return them or assign them. You cannot put a `let` declaration in a branch of a ternary.