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:
You might want to try and get the toppings for a non-existing barbecue pizza🍕, but you'll get 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 a value exists for "toppings", it will be returned as normal:
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)