How to avoid the JavaScript error “cannot read property ___ of undefined” without nesting logical AND (&&)

const object = {
name: 'Omar',
hobbies: {
sewing: {
favorite: true,
},
hiking: {
favorite: false,
frequency: 'often',
},
},
}
console.log(object.hobbies.fishing.frequency) // Throws errror: "TypeError: Cannot read property 'frequency' of undefined"
const object = {
name: 'Omar',
hobbies: {
sewing: {
favorite: true,
},
hiking: {
favorite: false,
frequency: 'often',
},
},
}
const fishingFrequency = object.hobbies && object.hobbies.fishing && object.hobbies.fishing.frequency
console.log(fishingFrequency) // returns undefined
const fishingFrequency = ((object.hobbies || {}).fishing || {}).frequency
console.log(fishingFrequency) // returns undefined

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store