Created
October 7, 2020 15:05
-
-
Save heytulsiprasad/5bf70473e299398dac918c8c761b72fe to your computer and use it in GitHub Desktop.
Learning about Optional Chaining
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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