javascript / beginner
Snippet
Guarding Against Missing Prop Values Using Nullish Coalescing
The nullish coalescing operator (??) provides safe fallback defaults only when a value is strictly null or undefined. This is preferred over logical OR (||) because it correctly preserves valid falsy values like 0 or empty strings.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
function ScoreDisplay({ score, defaultText }) {const resolvedScore = score ?? 0;const resolvedText = defaultText ?? 'Points';return (<div><span>{resolvedScore}</span> {resolvedText}</div>);}
react
Breakdown
1
const resolvedScore = score ?? 0;
Assigns score if defined; otherwise falls back to 0, correctly keeping an actual score of 0 intact.
2
const resolvedText = defaultText ?? 'Points';
Provides 'Points' as a fallback string whenever defaultText is nullish.
3
<span>{resolvedScore}</span> {resolvedText}
Safely renders the resolved values without risk of undefined runtime output.