Skip to content

Instantly share code, notes, and snippets.

@AviKKi
Created May 26, 2020 17:10
Show Gist options
  • Save AviKKi/c8a2f87967b0e484a6f1fa38b796209d to your computer and use it in GitHub Desktop.
Save AviKKi/c8a2f87967b0e484a6f1fa38b796209d to your computer and use it in GitHub Desktop.
SLIDE 1
Optional Chaining ?.
SLIDE 2
When you try to access a property of undefined or null you'll get an error
```js
const user1 = {
username: 'avikki_coder',
address: {
city: 'Banglore',
pinCode: '560007'
},
print(){ console.log(this.username+'😎') }
}
const user2 = {
username: 'cool_guy'
}
console.log(user1.address.city) // Banglore
user1.print() // avikki_coder😎
console.log(user2.address.city)
// ❌ Cannot read property 'city' of undefined
user2.print()
// ❌ user2.print is not a function
```
SLIDE 3
Best solutions in current JS version is to use &&
```js
console.log( user2.address && user2.address.city )
// undefined
// same for function call
user2.print && user2.print()
```
Expression evaluation works from left to right
Value of a && operation is falsy if any of the value is falsy
errors.username is undefined so expression after it is skipped.
🎉🎉 we didn't trigger any errors
but it is not a very good looking syntax
SLIDE 4
Optional Chaining to rescue😎
```js
console.log(user2?.address?.city) // undefined
user2.print?.()
```
If expression before ?. is undefined or null, anything after that is ignored and end result is undefined.
SLIDE 5
Like,
Comment your thoughts,
Share
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment