Optional chaining in Javascript, explained with pizza🍕

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:

pizza-object.png

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

chaining-fail.png

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.

chaining-success.png

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

chaining-success-2.png

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.