Skip to content
jshacks.dev
Fundamentals

Nullish Coalescing vs Logical OR in JavaScript Compared

Logical OR swaps every falsy value for a default, while nullish coalescing swaps only null and undefined. See which to use for zero, empty strings and false.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, npm, Vite and Node.js logos.

A page size of 0, a volume of 0, a flag set to false and a name set to the empty string are all legitimate settings, and value || default throws every one of them away. The bug is old and common: a function with const limit = options.limit || 20 cannot be told "no limit, zero". The ?? operator was added to fix it, and the choice between the two operators is the choice between "missing" and "falsy". This post compares them on every falsy value, shows the bugs and the cases where || is still correct, and covers the parenthesis rule. Examples run on Node.js 24. The list of falsy values is in the post on truthy and falsy values, and null and undefined are defined in their own post.

The difference on every value

Run both operators over the values that matter.

JavaScript
const values = [0, -0, "", false, NaN, null, undefined, "0", [], "text"];

const show = (value) => {
  if (value === "DEFAULT") return "DEFAULT";
  if (Object.is(value, -0)) return "-0";
  if (typeof value === "string") return JSON.stringify(value);
  if (Array.isArray(value)) return "[]";
  return String(value);
};

for (const value of values) {
  console.log(show(value).padEnd(10), show(value || "DEFAULT").padEnd(9), show(value ?? "DEFAULT"));
}
Text
0          DEFAULT   0
-0         DEFAULT   -0
""         DEFAULT   ""
false      DEFAULT   false
NaN        DEFAULT   NaN
null       DEFAULT   DEFAULT
undefined  DEFAULT   DEFAULT
"0"        "0"       "0"
[]         []        []
"text"     "text"    "text"

The columns are the input value, the result of || with a default, and the result of ?? with the same default. For 0, -0, "", false and NaN, || replaced the value with the default and ?? kept it. For null and undefined, both replaced it. For the truthy values, neither did. ?? has exactly two triggers, and that is easy to remember: it is the operator for "missing".

The default value bug

The failure shows up in configuration objects, where zero and false are meaningful.

JavaScript
function paginate(options) {
  const withOr = {
    pageSize: options.pageSize || 20,
    showTotal: options.showTotal || true,
    prefix: options.prefix || "page-",
  };

  const withNullish = {
    pageSize: options.pageSize ?? 20,
    showTotal: options.showTotal ?? true,
    prefix: options.prefix ?? "page-",
  };

  return { withOr, withNullish };
}

const result = paginate({ pageSize: 0, showTotal: false, prefix: "" });

console.log(result.withOr);
console.log(result.withNullish);
Text
{ pageSize: 20, showTotal: true, prefix: 'page-' }
{ pageSize: 0, showTotal: false, prefix: '' }

All three settings were deliberate, and the || version overrode every one. The showTotal line is the most insidious, because x || true can never be false, so the option is permanently on and the caller cannot turn it off. The ?? version honored all three. We changed every options default in our own code to ?? and the reports that a setting of zero was ignored stopped.

Where || is still the right choice

When an empty value should be treated as missing, || says exactly that. A form field that arrives as an empty string, a display name that should fall back when blank, and a computed number that might be NaN all want the broader test.

JavaScript
function displayName(user) {
  return user.nickname?.trim() || user.email;
}

console.log(displayName({ nickname: "Ada", email: "[email protected]" }));
console.log(displayName({ nickname: "   ", email: "[email protected]" }));
console.log(displayName({ email: "[email protected]" }));

const average = (list) => list.reduce((sum, n) => sum + n, 0) / list.length || 0;

console.log(average([2, 4]));
console.log(average([]));
Text
Ada
[email protected]
[email protected]
3
0

A nickname of only spaces trims to an empty string, which is falsy, so the email is used, and ?? would have kept the blank. The average of an empty list is 0 / 0, which is NaN, and || 0 turns that into a clean zero. Both are deliberate uses of falsiness, and we write a short comment on the second, since a reader may see || and assume the old bug.

Combining them needs parentheses

The language refuses to guess the precedence of ?? mixed with || or &&. Without parentheses it is a syntax error.

JavaScript
const attempts = [
  "null || undefined ?? 'x'",
  "(null || undefined) ?? 'x'",
  "null || (undefined ?? 'x')",
  "null ?? undefined ?? 'x'",
];

for (const source of attempts) {
  try {
    console.log(source.padEnd(30), "=>", eval(source));
  } catch (error) {
    console.log(source.padEnd(30), "=>", error.name);
  }
}
Text
null || undefined ?? 'x'       => SyntaxError
(null || undefined) ?? 'x'     => x
null || (undefined ?? 'x')     => x
null ?? undefined ?? 'x'       => x

The first form is rejected, and the two parenthesized forms are accepted and mean different things when the operands change. Chains of ?? alone are fine and evaluate left to right. The error is useful, because the mixed form was a source of bugs in other languages, and here you must say what you mean.

A rule you can apply without thinking

Ask what the left side can be and what you want for each case. If the only bad value is "missing", write ??. If "empty" is also bad, write ||, and a comment. If you are tempted to write || false or || true, stop, because a boolean default through || is a permanent value and almost always a bug. The cost of the wrong choice is asymmetric: choosing ?? where || was right lets an empty value through and produces a visible blank, while choosing || where ?? was right silently discards data the user entered. Prefer the visible failure.

Short-circuiting

Both operators skip the right-hand side when the left side is good enough. That makes either one a lazy default, which matters when computing the default is costly or has side effects.

JavaScript
let computed = 0;
const expensiveDefault = () => {
  computed += 1;
  return "default";
};

const a = "set" ?? expensiveDefault();
const b = 0 ?? expensiveDefault();
const c = 0 || expensiveDefault();
const d = null ?? expensiveDefault();

console.log(a, b, c, d);
console.log(computed);
Text
set 0 default default
2

The default function ran twice, for 0 || ... and for null ?? ..., and not for the first two, where the left side was acceptable. If the default is cheap, the laziness is academic. If it opens a connection or reads a file, it is the reason to use these operators over a ternary that evaluates both sides.

Defaults in function parameters

A parameter default applies only to undefined, which makes it equivalent to a narrower ??. It does not treat null as missing.

JavaScript
function connect(host = "localhost", port = 5432) {
  return host + ":" + port;
}

console.log(connect());
console.log(connect(undefined, 6432));
console.log(connect(null, null));

function connectSafe(host, port) {
  return (host ?? "localhost") + ":" + (port ?? 5432);
}

console.log(connectSafe(null, null));
Text
localhost:5432
localhost:6432
null:null
localhost:5432

connect(null, null) kept both null values, and the result mentions them. If the arguments can arrive as null from a database or JSON, parameter defaults are not enough, and an explicit ?? inside the function is. The post on destructuring shows that the same rule applies to destructuring defaults.

Environment variables and parsing

Environment variables are strings or undefined, never a number or null, so the operator choice interacts with parsing.

JavaScript
const env = { PORT: "0", RETRIES: "", DEBUG: undefined };

const port = Number(env.PORT ?? 3000);
const retries = Number(env.RETRIES || 3);
const retriesNullish = Number(env.RETRIES ?? 3);
const debug = (env.DEBUG ?? "false") === "true";

console.log(port, retries, retriesNullish, debug);
Text
0 3 0 false

A port of "0" survived ??, which is correct, since "0" is a non-empty string and would have survived || as well. An empty RETRIES is where they differ: || fell back to 3, and ?? kept the empty string, which Number("") turns into 0, almost certainly not intended. For environment variables, where an empty string usually means "unset", || is the better operator, and we say so in a comment.

Migrating a codebase from || to ??

The change is mechanical, and the risk is in the few places that relied on the broad behavior. Search for || followed by a literal default, and ask of each one what the left side can be. If it can be 0, false or "" and those are valid, switch to ??. If it is a string from a form or an environment variable where blank means unset, keep ||. If it is a boolean flag, check whether || true is hiding a permanent on switch, which is the most common real bug in the search. Run the tests after each file, and add a test with a zero and an empty string, since neither was ever exercised by the code that needed the default.

ESLint's @typescript-eslint/prefer-nullish-coalescing reports candidates and can fix them, and its options let you ignore cases where the left side is a primitive that may be falsy on purpose. Turn it on as a warning first, read the list, and promote it once the intentional uses carry a comment.

Where this advice stops

Neither operator validates anything. A default for a missing value does not help if the value is present and wrong, such as a string where a number is expected. Validate at the boundary and use the operators for what remains.

Do not use ?? on a value that cannot be null or undefined, such as the result of arithmetic, since the right side never runs and the reader will wonder why it is there. A lint rule, @typescript-eslint/no-unnecessary-condition, flags those. And in a chain with optional chaining, as in the post on ?., put ?? at the end to give the whole path a default.

The operator needs Node.js 14 or later and any browser from 2020 onward. The older || fallback remains valid on any runtime.

The operator is defined in the specification under binary logical operators, and MDN's page on nullish coalescing documents the precedence rule.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.