Skip to content

Instantly share code, notes, and snippets.

@Mahdhir
Last active November 2, 2020 15:57
Show Gist options
  • Save Mahdhir/e7ff3ea73d85ccb913b9ca18e3497f23 to your computer and use it in GitHub Desktop.
Save Mahdhir/e7ff3ea73d85ccb913b9ca18e3497f23 to your computer and use it in GitHub Desktop.
let book = {
name: "Harry Potter 1",
price: {
value: 50,
currency: "EUR"
},
ISBN: "978-7-7058-9615-2",
weight: {
version1: {
value: 550,
unit: 'g'
},
version2: {
value: 690,
unit: 'g'
}
}
}
if (book && book.weight && book.weight.version2 && book.weight.version2.value) {
//Do something with book.weight.version2.value
console.log(book.weight.version2.value);
}
if (book && book.weight && book.weight.version3 && book.weight.version3.value) {
//Since there is no version 3, this block would not run and throw any errors
console.log(book.weight.version3.value);
}
//Accessing without checking
console.log(book.weight.version3.value);
//error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment