DEV Community

Cover image for Optional chaining in Javascript, explained with pizza🍕
Jean-RĂ©my Duboc
Jean-RĂ©my Duboc

Posted on

1

Optional chaining in Javascript, explained with pizza🍕

When you wan to explorer an object in JS, you may need to go deep and "chain" multiple object properties.
Look at a delicious object like this for instance:

A JS object describing pizzas

You might want to try and get the toppings for a non-existing barbecue pizza🍕, but you'll get an error:

If we write pizzaOptions.barbecue.toppings, JS throws an error

Using optional chaining, you can essentially tell JS or TypeScript: look for toppings on this pizza, but just return "undefined" if the pizza doesn't exist.

If we write pizzaOptions.barbecue?.toppings, JS just returns undefined

If a value exists for "toppings", it will be returned as normal:

If we write pizzaOptions.margarita?.toppings, JS returns the toppings for margaritas

There you have it! Optional chaining is very useful when you're not sure what you have in your data objects, and you don't really mind if there's nothing there.

Check out the documentation on MDN for mor info.

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay