Photo by PJH on Unsplash

On this page

This chapter follows Operators in JavaScript.

if and else

Conditions coerce to boolean with the same rules as Boolean(value): falsy values are false, 0, -0, 0n, "", null, undefined, and NaN.

if.js
if (response?.status === 404) {
handleNotFound();
} else if (response?.status >= 500) {
handleServerError();
}

There is no elseif keyword—use else if chains.

switch and strict equality

switch (expr) compares expr to each case with ===. No type coercion. String "1" does not match numeric 1.

switch.js
switch (code) {
case 200:
ok();
break;
case 404:
notFound();
break;
default:
unknown();
}

Omitting break falls through to the next case—sometimes intentional for grouped cases, often a bug. Some teams prefer if/else or lookup objects to avoid fall-through mistakes.

switch true pattern

switch (true) with boolean cases replaces long if/else if chains when each branch is a predicate:

switch-true.js
switch (true) {
case score >= 90:
grade = "A";
break;
case score >= 80:
grade = "B";
break;
default:
grade = "C";
}

Ternary operator

The conditional condition ? consequent : alternate is an expression and can appear inside assignments and return statements.

ternary.js
const label = count === 1 ? "item" : "items";
return ok ? data : null;

Nested ternaries are legal but hard to read—prefer if/else or early returns for multi-branch logic.

Truthy shortcuts versus explicit checks

Because && and || return values, patterns like value && doSomething(value) are idiomatic. They differ from languages that require boolean contexts only in if. For APIs that accept 0 or "", combine with nullish coalescing or explicit comparisons instead of || defaults.

Labels, break, and continue

Labels name a statement for break label or continue label. The label applies to a statement (often a loop or switch), not to a block alone.

labels.js
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer;
}
}

continue outer jumps to the next iteration of the labeled loop. Unlabeled break/continue refer to the innermost switch or loop. These are rarely needed but replace some goto-like patterns from C.

Exceptions versus control flow

Use try/catch for exceptional paths, not for ordinary branching—Error handling in JavaScript covers that. return, throw, and break exit different structures; throw unwinds the call stack until a matching catch or the host reports an uncaught exception.

Next: Loops in JavaScript.

Search articles

Type a word to search published articles.

Open the search page