Is there a "null coalescing" operator in JavaScript?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Yes. JavaScript has a null coalescing operator, written as ??. It lets you provide a fallback only when the value on the left is null or undefined, which is often exactly what you want when working with optional data.
What ?? Does
The syntax is:
The rule is simple:
- if
leftValueis neithernullnorundefined, return it - otherwise return
fallbackValue
This makes ?? safer than older patterns that treat every falsy value as "missing".
Why It Is Different from Logical OR
Logical OR is based on truthiness. Null coalescing is based on nullishness.
So if 0, false, or the empty string are valid values in your program, ?? is usually the correct operator.
Common Use Cases
One of the most common uses is setting defaults without breaking valid falsy values:
That age: 0 example is exactly where ?? is better than logical OR.
?? and Optional Chaining
Null coalescing works especially well with optional chaining:
That expression:
- safely walks through nested properties
- falls back only if the final value is missing
This pattern is extremely common in frontend code and API handling.
Parentheses Matter
JavaScript does not allow ?? to be mixed directly with && or logical OR without parentheses.
This is invalid:
Write one of these instead:
The language forces you to be explicit so the intent is unambiguous.
Compatibility Notes
?? is part of modern JavaScript and is supported in current browsers and Node.js environments. If you still target older runtimes, you typically handle that through your build pipeline with Babel or a similar transpiler.
Common Pitfalls
- Replacing every
||with??. The two operators solve different problems. - Forgetting that
false,0, and""are preserved by??. - Mixing
??with&&or logical OR without parentheses. - Treating an API's falsy value as if it were missing data.
Summary
- JavaScript does have a null coalescing operator:
??. - It falls back only for
nullandundefined. - It is different from logical OR, which falls back for any falsy value.
- It pairs naturally with optional chaining.
- Parentheses are required when mixing it with
&&or logical OR.

