Skip to content

Instantly share code, notes, and snippets.

@katepapineni
Last active July 20, 2020 15:53
Show Gist options
  • Save katepapineni/d9508f5e14422bdbfd910968457b15f5 to your computer and use it in GitHub Desktop.
Save katepapineni/d9508f5e14422bdbfd910968457b15f5 to your computer and use it in GitHub Desktop.
/* Optional Chaining (?.) in ES2020 */
const app = {
frontend: {
language: 'JavaScript',
framework: 'ReactJS',
},
backend: {
language: 'Python',
},
database: {
name: 'MongoDB',
},
};
// Optional Chaining when property exists
const react = app.frontend?.framework;
console.log(react);
// Output => ReactJS
// Optional Chaining when property doesn't exist => no error thrown!
const analytics = app.frontend?.analytics;
console.log(analytics);
// Output => undefined
// Without Optional Chaining when property doesn't exist => error thrown!
const { docker } = app.deployment;
console.log(docker);
// Output => Error: Cannot read property 'docker' of undefined
// Without Optional Chaining => have to manually check for existance first to avoid an error
const kubernetes = app.deployment && app.deployment.kubernetes;
console.log(kubernetes);
// Output => undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment