?? vs || — Why Nullish Coalescing is Better for Default Values?

Mon, April 21, 2025 - 2 min read
Operator ?? vs ||

❓ ?? vs || — Choose Wisely

In JavaScript, we often set default values like this:

const value = input || 'default';

But this can be a trap.


⚠️ The Problem with ||

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 Solution — ??

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'

💡 When to Use ??

ScenarioKeep value?Use
0 is a valid valueYes??
Empty string '' is allowedYes??
Only null and undefined mean “missing”Yes??
Any falsy value means “missing”No||

🧪 Real-Life Examples

✅ Product Price

const price = product.price ?? 0; // fallback to 0 if undefined

✅ Input Value

const value = inputValue ?? ''; // allow empty string, but not undefined

✅ Padding in Pixels

const padding = props.padding ?? 10; // 0 is allowed

🔥 When is || Still Fine?

If any falsy value should be treated as “missing”, || works:

const isDark = userPrefersDark || false;

Here false, 0, '' — all mean “no”.


📝 Summary

  • 🛑 || doesn’t distinguish between false, 0, '', and undefined.
  • ?? only applies fallback for null or undefined.
  • 🤓 ?? is safer in most cases.
  • 📌 Use ?? 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!