javascript / intermediate
Snippet
Optional Chaining and Nullish Coalescing
Optional chaining (?.) stops evaluation if the reference is nullish, while nullish coalescing (??) provides a default value only for null or undefined.
snippet.js
1
2
3
const user = { profile: { name: 'Alice' } };const city = user.address?.city ?? 'Unknown';console.log(city);
Breakdown
1
user.address?.city
Safely checks for address before accessing city.
2
?? 'Unknown'
Sets fallback if the previous expression is null or undefined.