Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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