Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Created October 7, 2020 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heytulsiprasad/5bf70473e299398dac918c8c761b72fe to your computer and use it in GitHub Desktop.
Save heytulsiprasad/5bf70473e299398dac918c8c761b72fe to your computer and use it in GitHub Desktop.
Learning about Optional Chaining
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
// fiddle: https://jsfiddle.net/tulsiprasad/hou3jrf8/120
const user = {
firstName: "Jade",
lastName: "Wilson",
address: {
home: {
street: "2502 Bennie Dr",
state: "Pearson, Georgia(GA)",
tel: "(912) 534-5614"
},
work: {
street: "774 Poplar Grove Rd",
state: "Boone, North Carolina(NC)",
tel: "(828) 386-1840"
}
},
fullName: function() {
return `${this.firstName} ${this.lastName}`
},
pets: ["Whoosh", "Fluffy", "Bolt"]
}
console.log(user.address.school.state) // TypeError: Cannot read property 'state' of undefined
console.log(user.completeName()) // TypeError: user.completeName is not a function
console.log(user.pets[12].toLowerCase()) // TypeError: Cannot read property 'toLowerCase' of undefined
console.log(user.address["school"]["street"]) // TypeError: Cannot read property 'street' of undefined
console.log(user.address.school?.state) // undefined
console.log(user.completeName?.()) // undefined
console.log(user.pets[12]?.toLowerCase()) // undefined
console.log(user.address["school"]?.["street"]) // undefined
console.log(user.address?.home?.state?.lane) // undefined
console.log(user.pets?.[12]?.name) // undefined
console.log(user.fullName?.()) // Jade Wilson
console.log(user.address?.home?.state) // Pearson, Georgia(GA)
console.log(user.address?.["work"]?.["state"]) // Boone, North Carolina(NC)
console.log(user.pets?.[1]) // Fluffy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment