0 day streak
javascript / intermediate
Snippet

Defensive Programming with Optional Chaining in JSX

Optional chaining (?.) and Nullish coalescing (??) are essential for safely accessing deeply nested object properties in JSX without crashing on undefined data.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
const UserProfile = ({ user }) => {
return (
<div>
<h1>{user?.name ?? 'Guest'}</h1>
<p>{user?.settings?.theme || 'Default Theme'}</p>
<ul>{user?.posts?.map(p => <li key={p.id}>{p.title}</li>)}</ul>
</div>
);
};
react
Breakdown
1
user?.name ?? 'Guest'
Safely checks if user exists before accessing name, defaulting to 'Guest'.
2
user?.posts?.map(...)
Prevents errors if 'posts' is undefined or null during the map operation.