Skip to main content
0 reactions

How to Use the Nullish Coalescing Operator (??) in JavaScript

A card titled The ?? Operator, labelled JavaScript Basics, showing null ?? “Guest” giving Guest, 0 ?? 100 giving 0, and 0 || 100 giving 100.
The ?? Operator: A default value only for null or undefined.

The nullish coalescing operator, ??, gives a default for a missing value: value ?? fallback gives back fallback only when value is null or undefined. Every other value, including 0 and empty text, is kept.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
value ?? fallback
  • value: the value that may be missing.
  • ??: the nullish coalescing operator.
  • fallback: what you get when value is null or undefined.

See Nullish coalescing operator (??) (opens in a new tab) on MDN.

Prerequisites

The Example

Two values with defaults: a nickname that’s null, and a page count of 0, which is a real value. The file is defaults.js.

Step 1: Write the Code

defaults.jsJavaScript
const nickname = null;
const pages = 0;

console.log(nickname ?? "Guest");
console.log(pages ?? 100);

Each line gives a value a default with ??.

Step 2: Run It

TerminalBash
node defaults.js
OutputPlain text
Guest
0

nickname is null, so you get the default, Guest. pages is 0, which isn’t null or undefined, so it’s kept.

Common Mistakes

MistakeWhat happensDo this instead
Using || for a default|| also replaces 0 and empty text: pages || 100 gives 100Use ?? when 0 or empty text are real values

FAQ

Can I chain several ?? operators?

Yes. a ?? b ?? "default" gives the first value that isn’t null or undefined, or "default" when both are.

Conclusion

value ?? fallback fills in only a missing value. Reach for it instead of || whenever 0 or empty text count as real values.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments