JavaScript Optional Chaining

JavaScript Optional Chaining

Optional chaining is a new feature in JavaScript that allows developers to safely access nested properties of an object without causing errors if the property doesn't exist. It uses the "?" symbol to check if a property exists before accessing it.

Here's an example that demonstrates how optional chaining works:

In the above example, we are trying to access the zipCode property of the address object, but since it doesn't exist, the result would normally be TypeError: Cannot read property 'zipCode' of undefined. However, with optional chaining, the code will simply return undefined instead of throwing an error.

Optional chaining can also be used in a chain of nested properties, like this:

In this example, we are trying to access the status property of the last order in the orders array. However, since the array is not guaranteed to have a last element, and even if it does, the object may not have a status property, we use optional chaining to safely access the value.

Optional chaining is particularly useful when working with APIs or external data sources where the data may not always be consistent.

That's it for JavaScript Optional Chaining. Thanks for reading and learning ❤️