JavaScript Logical Operators: &&, ||, !, ?? and Short-Circuit Evaluation
How &&, || and ?? really work: they return one of their operands rather than true or false, short-circuit their right side, and differ in which values trigger a fallback. Also ! and !!, De Morgan's laws, guards, defaults, the React && 0 pitfall, and when to choose ?? over ||.
kvi5hnuCode Sprout team member8 min readOn this page
The logical operators combine conditions: "the user is logged in and has permission", "use the saved value or a default". In many languages they always return true or false. In JavaScript, &&, || and ?? do something more useful: they return one of their operands, and they evaluate the right operand only when needed. Once you understand those two facts, idioms like name || "guest" and user && user.name stop being magic.

Logical AND: &&
a && b evaluates a. If a is falsy, it returns a and never looks at b. Otherwise it returns b.
With booleans, that's ordinary AND: true only if both sides are true. With other values, the result is one of the operands themselves:
console.log(true && false, 3 > 1 && 2 > 1);
console.log("cat" && "dog", 0 && "dog", null && "dog");
false true
dog 0 null
Recall the falsy values (article 17): false, 0, -0, 0n, "", null, undefined and NaN. Everything else, including "0", [] and {}, is truthy.
Guards: only continue if the left side is there
Because && stops at the first falsy value, it can protect the right side from running on something unusable:
const user = null;
console.log(user && user.name); // null: user.name is never evaluated
const nums = [1, 2, 3, 4];
console.log(nums.filter((n) => n > 1 && n < 4));
null
[ 2, 3 ]
For property access, optional chaining (user?.name, article 29) is now the clearer way to write a guard. && remains the natural choice for combining conditions.
The && rendering pitfall
In React and similar UI code, {condition && <Thing />} renders the component only if condition is truthy. But && returns its left operand when it's falsy, and React renders the number 0:
const unread = 0;
console.log(unread && "You have messages"); // 0, not false
console.log(unread > 0 && "You have messages"); // a real boolean on the left
0
false
React doesn't render false, null or undefined, but it renders 0, so users see a stray "0" on the page. Make the left side a real boolean: unread > 0 && ... or Boolean(unread) && ....
Logical OR: ||
a || b evaluates a. If a is truthy, it returns a and never evaluates b. Otherwise it returns b.
console.log(false || true, "" || "guest", "Ana" || "guest");
console.log(null || undefined, 0 || "" || null);
true guest Ana
undefined null
When every operand is falsy, || returns the last one. The classic idiom is picking the first usable value from a list of alternatives:
const displayName = profile.nickname || profile.fullName || "Anonymous";
This works perfectly when every falsy value means "not set". When 0, "" or false are valid values, it's a bug, and that's what ?? fixes.
Nullish coalescing: ??
a ?? b (ES2020) returns b only when a is null or undefined ("nullish"). Any other value, including 0, "", false and NaN, is kept:
const options = { timeout: 0, title: "", verbose: false, retries: null };
console.log(options.timeout || 1000, options.timeout ?? 1000);
console.log(options.title || "Untitled", options.title ?? "Untitled");
console.log(options.verbose || true, options.verbose ?? true);
console.log(options.retries || 3, options.retries ?? 3, options.missing ?? 3);
1000 0
Untitled
true false
3 3 3
With ||, the user's deliberate timeout: 0 (no timeout), empty title and verbose: false are all thrown away. With ??, they're respected; only the null and the missing property fall back. (The second line ends with the empty title, which prints as nothing.)
Choosing between them:
- Use
??for defaults: configuration, function options, API fields, anything where0,""orfalsecould be meaningful. This is the right default in modern code. - Use
||when you want every falsy value replaced, such as treating an empty input string as "no name given".
?? chains like ||: a ?? b ?? c returns the first operand that isn't nullish. It can't be mixed with && or || without parentheses (article 30).
?? pairs naturally with optional chaining: ?. produces undefined when something is missing, and ?? replaces it:
const theme = user?.settings?.theme ?? "light";
Short-circuit evaluation
All three operators evaluate their right operand only if it becomes the result. That's called short-circuiting, and it means side effects on the right may or may not happen:
const ran = [];
const op = (label, value) => { ran.push(label); return value; };
op("A", 0) && op("B", 1); // A is falsy: B skipped
op("C", 2) || op("D", 3); // C is truthy: D skipped
op("E", null) ?? op("F", 4); // E is nullish: F runs
op("G", 0) ?? op("H", 5); // G isn't nullish: H skipped
console.log(ran.join(" "));
A C E F G
You'll see this used deliberately to run code conditionally:
isDebug && console.log("state:", state); // log only in debug mode
cache.get(key) || loadFromServer(key); // load only on a cache miss
It's legal and common in minified code, but an if statement is usually clearer for side effects, and ESLint's no-unused-expressions rule, when enabled, flags these lines unless its allowShortCircuit option is on. Keep the operators for producing values.
Logical NOT: !
!x converts x to a boolean and inverts it. Unlike && and ||, it always returns true or false. Applying it twice, !!x, converts any value to its boolean equivalent, the same as Boolean(x):
console.log(!"", !"0", !0, ![]);
console.log(!!"0", !![], !!NaN, Boolean("false"));
true false true false
true true false true
Boolean(x) is easier to read; !!x is shorter and common. Both are fine. (Boolean("false") is true: a non-empty string is truthy whatever it says.)
! binds very tightly, so negating a larger expression needs parentheses: !(a && b), and !(key in obj) (article 30).
De Morgan's laws
Two equivalences help when simplifying or negating conditions:
!(a && b)is the same as!a || !b!(a || b)is the same as!a && !b
for (const a of [true, false]) {
for (const b of [true, false]) {
console.log(a, b, !(a && b) === (!a || !b), !(a || b) === (!a && !b));
}
}
true true true true
true false true true
false true true true
false false true true
So "not (logged in and admin)" is "not logged in, or not admin". Use this to remove a negation that wraps a whole condition: if (!(age >= 18 && hasId)) reads better as if (age < 18 || !hasId).
Mixing && and ||
&& has higher precedence than ||, so a || b && c means a || (b && c). A related idiom imitates the conditional operator, and has a trap:
console.log(true && "yes" || "no", false && "yes" || "no");
console.log(true && "" || "no"); // "" is falsy, so you get "no" even though the condition is true
yes no
no
cond && x || y only works when x is truthy. Use the real conditional operator, cond ? x : y (article 37).
Common questions
Why does && return a value instead of true/false?
It makes the operators useful for defaults and guards, and costs nothing in conditions: if, while and the ternary operator only care whether the result is truthy, so if ("cat" && "dog") behaves exactly as if (true). Use Boolean(...) when you need a real boolean, for example to store it or send it as JSON.
Is x ?? y the same as x !== null && x !== undefined ? x : y?
Yes, except that ?? evaluates x only once. If x is a function call or has side effects, the long form would run it twice.
Are there assignment versions of these operators?
Yes: a ||= b, a &&= b and a ??= b (ES2021). options.retries ??= 3 sets a default only if the property is nullish. The next article covers them, including a subtle difference from a = a ?? b.
Should I replace every || with ???
Not blindly. Replace it where 0, "", false or NaN should be kept. Where they should be replaced too (an empty search box meaning "search everything"), || is correct. Some linters, such as typescript-eslint's prefer-nullish-coalescing, flag the likely-wrong cases for you.
Summary
a && breturnsaif it's falsy, otherwiseb.a || breturnsaif it's truthy, otherwiseb. Neither necessarily returns a boolean.a ?? breturnsbonly ifaisnullorundefined, keeping0,"",falseandNaN. Prefer it for defaults.- All three short-circuit: the right side runs only if it becomes the result.
!xalways returns a boolean;!!xandBoolean(x)convert to one.- De Morgan:
!(a && b)equals!a || !b, and!(a || b)equals!a && !b. - Watch out for
0 && ...in UI code and forcond && x || ywhenxis falsy.
Practice Questions
What do "" || 0 || "x", "" ?? 0 ?? "x" and 1 && "" && 2 evaluate to?
Answer
"x", "" and "". || skips falsy values until "x"; ?? keeps the first non-nullish value, the empty string; && stops at the first falsy value, "".
A function receives limit, which may be undefined. Callers may pass 0 to mean "no results". Write the default of 20 correctly.
Answer
const pageSize = limit ?? 20;. With limit || 20, a deliberate 0 would become 20. A default parameter, function list(limit = 20), also works, since defaults apply only to undefined (article 18).
How many times is getConfig called in this expression if it returns null, and if it returns { a: 1 }?
getConfig() || getConfig() || {}
Answer
Twice if it returns null (both calls are falsy, so {} is the result), and once if it returns an object (the first operand is truthy, so the rest is skipped). Store the result in a variable to avoid calling it twice.
Simplify this code using De Morgan's law.
if (!(isOpen || isAdmin)) deny();
Answer
if (!isOpen && !isAdmin) deny();: deny only when the store is closed and the user isn't an admin.
Why does this code show "0" in a React app with an empty list, and how do you fix it?
{items.length && <List items={items} />}
Answer
items.length is 0, which is falsy, so && returns 0, and React renders numbers. Use a boolean on the left: items.length > 0 && <List ... />.
Previous: JavaScript Comparison Operators: <, >, String Ordering, in and instanceof
Next: JavaScript Assignment Operators: =, Compound Assignment and Logical Assignment (&&=, ||=, ??=)

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.