Nullish Coalescing and Optional Chaining in Modern JS
xRdev_38

xRdev_38 @xrdev38

Joined:
Mar 15, 2022

Nullish Coalescing and Optional Chaining in Modern JS

Publish Date: Jun 23
0 0

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!

Comments 0 total

    Add comment