?? vs || — Why Nullish Coalescing is Better for Default Values?
In JavaScript, we often set default values like this:
const value = input || 'default';
But this can be a trap.
||
The ||
operator returns the first “truthy” value.
So if input
is ''
(empty string) or 0
(zero), it treats them as false and replaces them.
console.log(0 || 10); // 10
console.log('' || 'default'); // 'default'
❗️ That’s not always the behavior you want.
??
The nullish coalescing operator (??
) works differently:
It provides the default value only if the variable is null
or undefined
, not just “falsy”.
console.log(0 ?? 10); // 0
console.log('' ?? 'default'); // ''
console.log(undefined ?? 'fallback'); // 'fallback'
??
Scenario | Keep value? | Use |
---|---|---|
0 is a valid value | Yes | ✅ ?? |
Empty string '' is allowed | Yes | ✅ ?? |
Only null and undefined mean “missing” | Yes | ✅ ?? |
Any falsy value means “missing” | No | ❌ || |
const price = product.price ?? 0; // fallback to 0 if undefined
const value = inputValue ?? ''; // allow empty string, but not undefined
const padding = props.padding ?? 10; // 0 is allowed
||
Still Fine?If any falsy value should be treated as “missing”, ||
works:
const isDark = userPrefersDark || false;
Here false
, 0
, ''
— all mean “no”.
||
doesn’t distinguish between false
, 0
, ''
, and undefined
.??
only applies fallback for null or undefined.??
is safer in most cases.??
if you want to keep 0
, false
, or ''
.The ??
operator is the modern standard for default values.
Don’t let falsy values trick you 🙃
📘 Want more practical tips like this? Follow Telegram channel and check out my other articles!