Safely Access a Property on a JavaScript Array with Optional Chaining

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet

You can use optional chaining to access elements in an array. If the array is null or undefined, attempting to access an element with optional chaining prevents an error from being thrown, returning undefined instead.

Laurie Barth: [0:00] Define an array with the elements 1, 2, and 3. We can access the first element of the array index zero. If we define a new array that's null and attempt to access the first element, we'll get an error. Instead, we can use optional chaining, ?., to access that element. Now we will safely receive undefined.