🎉
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 // undefinedSetting Props
Optional chaining cannot appear in the left hand side of an assignment operator.
obj.prop1.prop2?.prop3 = 1 // throws compile time errorArrays
const myClass = {
students: [{ name: 'Gilfoyle' }],
}myClass.students?.[0] // { name: 'Gilfoyle' }
myClass.teachers?.[0] // undefinedCalling Methods
const api = {
init() {
// ...
},
name: 'my-api',
}api.init?.() // calls init
api.destroy?.() // undefined
api.name?.() // throws type errorMore Examples
myClass.students?.[0]?.nameWill return undefined if:
studentsis undefinedstudents[0]is undefinedstudents[0].nameis undefined
const nullish = null
let counter = 0
nullish?.[counter++] // undefined
counter // 0