Skip to content

Instantly share code, notes, and snippets.

@theptrk
Last active May 20, 2020 16:06
Show Gist options
  • Save theptrk/eac28f368093f340bda69dc14cfb1703 to your computer and use it in GitHub Desktop.
Save theptrk/eac28f368093f340bda69dc14cfb1703 to your computer and use it in GitHub Desktop.
Optional Chaining in javascript - avoid crashing your app
// This is an example of Optional Chaining
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined <- this is better than crashing your app
const dogName = adventurer.dog.name;
// expected output: Uncaught TypeError: Cannot read property 'name' of undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment