DEV Community

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

Posted on

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.

Top comments (0)