Last active
July 20, 2020 15:53
-
-
Save katepapineni/d9508f5e14422bdbfd910968457b15f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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