Nullish Coalescing and Optional Chaining in Modern JS
Two handy tools for safer, cleaner code and avoiding null/undefined errors.
Nullish Coalescing (??
)
const price = product.price ?? 0;
// price will be 0 if product.price is null or undefined
Optional Chaining (?.
)
const email = user?.profile?.email;
// Returns undefined if user or profile doesn't exist
Conclusion
Combine these two operators to easily handle uncertain values in JS!
Top comments (0)