0 day streak
javascript / beginner
Snippet

Safe Access with Optional Chaining

Optional chaining (?.) prevents errors when trying to access properties of an object that might be null or undefined. It stops and returns undefined instead of crashing.

snippet.js
javascript
1
2
const userCity = user?.address?.city;
return <p>Location: {userCity || 'Unknown'}</p>;
react
Breakdown
1
user?.address
Checks if 'user' exists before trying to look for 'address'.
2
|| 'Unknown'
A fallback value used if the result of the chaining is undefined.