Skip to content

Instantly share code, notes, and snippets.

@jmhungdev
Last active August 16, 2020 00:19
Show Gist options
  • Save jmhungdev/30e081b75f89e88d92909de41784021a to your computer and use it in GitHub Desktop.
Save jmhungdev/30e081b75f89e88d92909de41784021a to your computer and use it in GitHub Desktop.
Optional Chaining - ES2020 - Chrome 80+
// Use case: when dealing with deeply nested objects.
// example: { dog : { cat : { parrot : peacock }}}
let obj = { dog : { cat : { parrot : 'peacock' }}};
let iWantPeacock = obj.dog.cat.parrot; //can throw an error
// Alternatively, one can do preliminary checks before the assignment
if(obj && obj.dog && obj.dog.cat) {
let iWantPeacock = obj.dog.cat.parrot
}
// Now an easier and graceful way of doing this is called optional chaining
// it will return undefined if an error was thrown, else it will return the string peacock
let iWantPeacock = obj?.dog?.cat?.parrot
//This new syntax is part of ES2020, now supported natively in chrome80+, firefox74+, safari13.1+, node14+
//more info: https://v8.dev/features/optional-chaining
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment