JavaScript Course
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?

Flash Cards

Question

What does Nullish mean?

Click to reveal answer
Answer

Nullish refers specifically and exclusively to the values `null` and `undefined`. Unlike 'Falsy', it does not include `0`, `false`, `NaN`, or empty strings.

Question

Can you chain ?? and || together?

Click to reveal answer
Answer

Yes, but you MUST use parentheses to explicitly indicate precedence, e.g., `(a ?? b) || c`. If you try `a ?? b || c` without parentheses, it throws a SyntaxError.