DEV Community

xRdev_38
xRdev_38

Posted on

Nullish Coalescing and Optional Chaining in Modern JS

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 
Enter fullscreen mode Exit fullscreen mode

Optional Chaining (?.)

const email = user?.profile?.email; // Returns undefined if user or profile doesn't exist 
Enter fullscreen mode Exit fullscreen mode

Conclusion

Combine these two operators to easily handle uncertain values in JS!

Top comments (0)