Skip to content

Instantly share code, notes, and snippets.

@Ebazhanov
Last active August 5, 2021 19:38
Show Gist options
  • Save Ebazhanov/a0fffdfe59a01496496062b1dd74c510 to your computer and use it in GitHub Desktop.
Save Ebazhanov/a0fffdfe59a01496496062b1dd74c510 to your computer and use it in GitHub Desktop.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
// short way to make property dog optional
const dogName = (adventurer && adventurer.dog && adventurer.dog.name);
// previous solution
console.log(dogName);
// expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment