The optional chaining operator

05/05/2020 1 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

// Optional Chaining - 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

// Optional Chaining - 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.

Related Posts