JavaScript Nullish Coalescing
By Flavio Copes
Learn the JavaScript nullish coalescing operator (??) and how it sets a default value only when the left side is null or undefined, unlike falsy-based ||.
The nullish coalescing operator ?? returns the value on its right only when the value on its left is null or undefined. Any other value, including falsy ones like 0 and '', passes through untouched.
Have you ever used || to set a default value if a variable was null or undefined?
For example, like this:
const myColor = color || 'red'
Nullish coalescing replaces || in there:
const myColor = color ?? 'red'
Why not just use ||?
There is a whole range of bugs that hide underneath the surface when using || to provide a fallback value.
In short, || handles values as falsy. ?? handles values as nullish (hence the name).
With || the second operand is evaluated if the first operand is undefined, null, false, 0, NaN or ''.
?? limits this list to only undefined and null.
That difference matters more than it looks. Say you store a volume setting, and the user turns the volume all the way down to 0:
const saved = 0
const volume1 = saved || 50
const volume2 = saved ?? 50
console.log(volume1) // 50
console.log(volume2) // 0
|| sees 0, treats it as falsy, and throws away a value the user chose on purpose. ?? keeps it, because 0 is not null or undefined.
The same happens with empty strings. If someone clears a text field, '' is a real value. || would replace it with your default. ?? would not.
My advice is to reach for ?? whenever 0, false or '' are valid values in your program. Use || only when you really want to reject every falsy value.
The ??= assignment operator
There’s also a shorthand to assign a default only when a variable is currently null or undefined:
let options
options ??= { theme: 'dark' }
console.log(options) // { theme: 'dark' }
If options already had a value, ??= leaves it alone.
One pitfall to watch for
You can’t mix ?? with && or || in the same expression without parentheses. JavaScript refuses to guess which one runs first and raises a syntax error:
const result = count || fallback ?? 10
// SyntaxError: Unexpected token '??'
Wrap the part you want evaluated first:
const result = (count || fallback) ?? 10
Now it runs fine.
Related posts about js: