Safely Access a Property on a JavaScript Object with Optional Chaining

Laurie Barth
InstructorLaurie Barth

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

You can use optional chaining to access properties of an object. If the parent property exists, it acts as a typical dot accessor. If not, optional chaining prevents an error from being thrown and instead returns undefined.

Laurie Barth: [0:01] Define an object with an internal key-value pair {node: 1}. Object.node is equivalent to 1. If we use optional chaining ?., we still get 1.

[0:17] Define a new object that's null. If we attempt to access node on this object, we'll get an error. If we use optional chaining, we'll instead receive undefined.