Nullish Coalescing Operator (??) in JavaScript

🔍 What is the Nullish Coalescing Operator?

The ?? operator is a logical operator introduced in ES2020 that returns the right-hand operand when the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.

Note

It’s useful for setting default values only when a variable is null or undefined, unlike || which treats other falsy values (like 0 or "") as default triggers.

📚 Syntax

Code Snippet

let result = value1 ?? value2;

⚙️ How It Works

- If value1 is NOT null or undefined, result is value1. - Otherwise, result is value2.

🧪 Examples

Example 1: Basic Usage

let userInput = null;
let defaultValue = "Guest";

let name = userInput ?? defaultValue;
console.log(name); // "Guest"

Example 2: Differentiating from ||

let zero = 0;
console.log(zero || 42);   // 42 (0 is falsy, so default used)
console.log(zero ?? 42);   // 0  (0 is NOT null or undefined)

📌 When to Use

  • Use ?? when you want to assign a default only if a value is null or undefined.
  • Avoid using || when 0, "", or false are valid values you want to keep.

⚠️ Important Notes

  • The ?? operator cannot be directly mixed with && or || without parentheses due to syntax rules.
  • It only checks for null and undefined, not other falsy values.

🧾 Summary

  • ?? returns the right operand if the left is null or undefined.
  • It’s safer than || for defaulting values where falsy values are valid.
  • Use it to avoid unintended fallback on values like 0, "", or false.
>>“Nullish coalescing brings clarity and precision to default value handling.”

🔗 References