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
value ?? fallback
value: the value that may be missing.??: the nullish coalescing operator.fallback: what you get whenvalueisnullorundefined.
See Nullish coalescing operator (??) (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
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
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
node defaults.js
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
| Mistake | What happens | Do this instead |
|---|---|---|
Using || for a default | || also replaces 0 and empty text: pages || 100 gives 100 | Use ?? 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
- Nullish coalescing operator (??) (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments