<em>Optional Chaining</em> Tips

Syntax Getting Props Setting Props Optional chaining cannot appear in the left hand side of an assignment operator. Arrays Calling Methods…


This content originally appeared on Things I've Learnt and was authored by Things I've Learnt

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


This content originally appeared on Things I've Learnt and was authored by Things I've Learnt


Print Share Comment Cite Upload Translate Updates
APA

Things I've Learnt | Sciencx (2020-01-05T00:27:09+00:00) <em>Optional Chaining</em> Tips. Retrieved from https://www.scien.cx/2020/01/05/emoptional-chaining-em-tips/

MLA
" » <em>Optional Chaining</em> Tips." Things I've Learnt | Sciencx - Sunday January 5, 2020, https://www.scien.cx/2020/01/05/emoptional-chaining-em-tips/
HARVARD
Things I've Learnt | Sciencx Sunday January 5, 2020 » <em>Optional Chaining</em> Tips., viewed ,<https://www.scien.cx/2020/01/05/emoptional-chaining-em-tips/>
VANCOUVER
Things I've Learnt | Sciencx - » <em>Optional Chaining</em> Tips. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2020/01/05/emoptional-chaining-em-tips/
CHICAGO
" » <em>Optional Chaining</em> Tips." Things I've Learnt | Sciencx - Accessed . https://www.scien.cx/2020/01/05/emoptional-chaining-em-tips/
IEEE
" » <em>Optional Chaining</em> Tips." Things I've Learnt | Sciencx [Online]. Available: https://www.scien.cx/2020/01/05/emoptional-chaining-em-tips/. [Accessed: ]
rf:citation
» <em>Optional Chaining</em> Tips | Things I've Learnt | Sciencx | https://www.scien.cx/2020/01/05/emoptional-chaining-em-tips/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.