0
0
JavascriptConceptBeginner · 3 min read

Nullish Coalescing Operator in JavaScript: What It Is and How to Use

The nullish coalescing operator (??) in JavaScript returns the right-hand value only if the left-hand value is null or undefined. It helps provide default values without mistakenly treating other falsy values like 0 or '' as null.
⚙️

How It Works

The nullish coalescing operator ?? checks if a value is either null or undefined. If it is, it returns the value on its right side; otherwise, it returns the left value.

Think of it like asking, "Is this value missing or empty?" If yes, then use a backup value. But if the value is something like zero, an empty string, or false, it keeps that value because those are valid and intentional.

This is different from the logical OR || operator, which treats many values like 0, '', or false as false and replaces them, which can cause unexpected results.

💻

Example

This example shows how ?? returns the right value only if the left is null or undefined, but keeps other falsy values.

javascript
const a = 0;
const b = a ?? 42;
console.log(b); // 0

const c = null;
const d = c ?? 42;
console.log(d); // 42

const e = undefined;
const f = e ?? 42;
console.log(f); // 42

const g = '';
const h = g ?? 'default';
console.log(h); // ''
Output
0 42 42 ''
🎯

When to Use

Use the nullish coalescing operator when you want to provide a default value only if a variable is null or undefined. This is useful when 0, false, or empty strings are valid values you want to keep.

For example, when reading user input or configuration settings, you might want to keep 0 as a valid number but still provide a default if the value is missing.

Key Points

  • Only treats null and undefined as missing values.
  • Does not replace other falsy values like 0, false, or ''.
  • Helps avoid bugs caused by using || when falsy values are valid.
  • Introduced in ES2020 and widely supported in modern JavaScript environments.

Key Takeaways

The nullish coalescing operator (??) returns the right value only if the left is null or undefined.
It preserves valid falsy values like 0, false, and empty strings without replacing them.
Use it to provide default values safely without unintended overrides.
It is different from the logical OR (||) operator which treats many falsy values as missing.
Supported in modern JavaScript since ES2020.