The optional chaining operator

The optional chaining operator

Published: 5/5/20201 min read
JS

Tired of seeing Uncaught TypeError: Cannot read property 'someProperty' of undefined ? and what about checking objects and/or arrays for nullish values? and what if you have to chain through an objects properties just to get that one desired value? Fear not! The optional chaining operator ?. allows us to check for nullish values (null or undefined) without having to nest if's or perform many type checks.
The optional chaining operator can be applied to objects, arrays, and functions. Here are some examples of applying the operator:

Objects

const person = {
  id: 1,
  name:{
    first: 'X Æ A-12'
  }
}

console.log(person.title.last); // output: Uncaught TypeError: Cannot read property 'last' of undefined
// However
console.log(person.title?.last); // output: undefined

BTW, X Æ A-12, is a real name.

Functions

let str = 'Hello there';

console.log(str.toSlug()); // output: Uncaught TypeError: str.toSlug is not a function
// However
console.log(str.toSlug?.()); // output: undefined

👉 More great info and examples here.