javascript / intermediate
Snippet
Distinguishing Nullish Coalescing from Logical OR in Conditional JSX Rendering
In JavaScript, `0`, `""`, and `false` are falsy values. Using the logical OR operator (`||`) in JSX fallback expressions causes numeric zero counts to be replaced with fallback text. The nullish coalescing operator (`??`) specifically checks only for `null` and `undefined`.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React from 'react';export function UserMetricBadge({ count, label, unreadCount }) {// Logical OR (||) treats 0 as falsy, triggering the fallback incorrectlyconst faultyCountDisplay = count || 'No data';// Nullish coalescing (??) only triggers on null or undefined, preserving 0const safeCountDisplay = count ?? 'N/A';// Optional chaining (?.) paired with ?? handles deeply nested fallbacks safelyconst badgeText = unreadCount?.badge ?? 0;return (<div className="metric-badge"><span className="label">{label}:</span><span className="value">{safeCountDisplay}</span><span className="unread">Unread: {badgeText}</span></div>);}
react
Breakdown
1
const faultyCountDisplay = count || 'No data';
Evaluates to 'No data' if count is 0, because 0 is falsy in JavaScript boolean coercion.
2
const safeCountDisplay = count ?? 'N/A';
Evaluates to 0 if count is 0, only falling back to 'N/A' when count is null or undefined.
3
const badgeText = unreadCount?.badge ?? 0;
Safely reads a nested property using optional chaining and provides a default value.