JavaScript
/Intermediate
Nullish Coalescing
Definition
The `??` operator is a logical operator that returns its right-hand operand when its left-hand operand is null or undefined, and otherwise returns its left-hand operand.
Explain Like I'm New
It's a stricter version of the `||` operator. The `||` operator falls back on ANY falsy value (like `0` or `""`). The `??` operator only falls back if the value is specifically `null` or `undefined`.
Real World Example
Setting a game score. If you use `score || 100`, a player with a genuine score of `0` will be accidentally given `100` because `0` is falsy. Using `score ?? 100` correctly preserves the `0`.
Common Use Cases
- •Providing default values
- •Working alongside Optional Chaining
Terminal Output
bash / terminal
const count = 0;
const message = "";
// Logical OR (||) treats 0 and "" as falsy
console.log(count || 100); // 100 (Oops, lost the 0)
console.log(message || "Hi"); // "Hi" (Oops, lost the empty string)
// Nullish Coalescing (??) only replaces null/undefined
console.log(count ?? 100); // 0 (Correct!)
console.log(message ?? "Hi"); // "" (Correct!)
let missingData = null;
console.log(missingData ?? "Fallback data"); // "Fallback data"
Interview Questions
basic
- What is the difference between `||` and `??`?
intermediate
- What does the word 'Nullish' mean?
advanced
- Can you chain `??` and `||` together in the same expression?