JS Tip of the Day: Optional Chaining

Optional Chaining
Version: ES2020
Level: Intermediate

To start off the tip of the day list, we’ll start with a brand new feature of JavaScript that only just recently got approved for the JavaScript (ECMAScript) standard: optional chaining!

Optional chaining is a brand new JavaScript feature introduced in ES2020 that lets you safely dig down into an object reference without having to worry about whether or not any objects within the path are not available or undefined.

Normally, if you attempt to access a property of an object that doesn’t exist, you’ll get an error.

let empty = {};
let x = empty.something.x;
// TypeError: Cannot read property 'x' of undefined

Here, because something is undefined on empty, a type error occurs when accessing x. The optional chaining operator (?.) allows you to attempt the same object reference but will return undefined rather than throwing an error.

let empty = {};
let x = empty?.something?.x;
console.log(x); // undefined

This makes it easier to look for a deeply nested value without having to check each object reference along the way or wrap your code in a try...catch block. But be careful, this approach doesn’t differentiate between there not being a variable (or object along the way) and the variable existing but having a value of undefined.

Optional chaining works in other situations as well, including, but not limited to, function calls.

More info:

1 Like