dutzi.party

🎉

Optional Chaining Tips

January 05, 2020

Syntax

obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)

Getting Props

const obj = {
  prop1: {
    prop2: {
      prop3: 'nested-value',
    },
  },
}
obj.doesNotExist?.prop2?.prop3 // undefined
obj.doesNotExist?.prop2.prop3  // undefined, doesn't throw
obj.doesNotExist?.['prop2'].prop3  // undefined

Setting Props

Optional chaining cannot appear in the left hand side of an assignment operator.

obj.prop1.prop2?.prop3 = 1 // throws compile time error

Arrays

const myClass = {
  students: [{ name: 'Gilfoyle' }],
}
myClass.students?.[0] // { name: 'Gilfoyle' }
myClass.teachers?.[0] // undefined

Calling Methods

const api = {
  init() {
    // ...
  },
  name: 'my-api',
}
api.init?.()    // calls init
api.destroy?.() // undefined
api.name?.()    // throws type error

More Examples

myClass.students?.[0]?.name

Will return undefined if:

  • students is undefined
  • students[0] is undefined
  • students[0].name is undefined
const nullish = null
let counter = 0

nullish?.[counter++] // undefined
counter              // 0