React / React Conditionals / Nullish Coalescing Operator
Home /React /React Conditionals /Nullish Coalescing Operator

Nullish Coalescing Operator

Nullish Coalescing Operator ??

The nullish coalescing operator (??) returns the right-hand fallback only when the left-hand value is null or undefined. Unlike ||, it does NOT treat 0, false, or "" as nullish making it much safer for numeric and boolean values.

function ScoreCard({ score, label, active }) {
  return (
    <div>
      {/* score = 0: || shows fallback, ?? shows 0 correctly */}
      <p>With ||: {score || 'No score'}</p>  {/* "No score" ❌ */}
      <p>With ??: {score ?? 'No score'}</p>  {/* 0 ✓     */}

      {/* label = "": || uses fallback, ?? keeps empty string */}
      <p>Label: {label ?? 'Default label'}</p>

      {/* active = false: || uses fallback, ?? keeps false */}
      <p>Active: {String(active ?? true)}</p>

      {/* Nullish with optional chaining — safe deep access */}
      <p>City: {user?.address?.city ?? 'City not set'}</p>
    </div>
  );
}

Comparison: || vs ??

Value Using || (OR) Using ?? (Nullish)
null Uses fallback Uses fallback
undefined Uses fallback Uses fallback
0 Uses fallback (likely wrong) Keeps 0
"" (empty string) Uses fallback Keeps “”
false Uses fallback Keeps false
"hello" Keeps “hello” Keeps “hello”