Access Long Chains of Properties with JavaScript Optional Chaining

Shruti Kapoor
InstructorShruti Kapoor
Share this video with your friends

Social Share Links

Send Tweet

Accessing a long chain of properties can be risky since one or more properties could be undefined or null. To be safe, we can use optional chaining when accessing long chain of properties.

Instructor: [0:00] Optional chaining can be used to chain properties that maybe now are undefined. It is especially useful for accessing a long chain of properties. like here.

[0:13] Consider this example, there are long chains being accessed, and there are multiple points of failure in the statement. Any of the properties in this long chain could be null or undefined. Then, we try to access them. JavaScript then throw an error.

[0:31] To fix this, we can use optional chaining while accessing properties, and now JavaScript returns undefined if any one of these properties is null or undefined.