Nullish Coalescing Operator in JavaScript: What It Is and How to Use
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.
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); // ''
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
nullandundefinedas 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.