Skip to content

Instantly share code, notes, and snippets.

@thawkin3
Last active April 15, 2020 19:51
Show Gist options
  • Save thawkin3/f63144ad4ab85aee50f13bf4476a549e to your computer and use it in GitHub Desktop.
Save thawkin3/f63144ad4ab85aee50f13bf4476a549e to your computer and use it in GitHub Desktop.
Accessing deeply nested object properties without the optional chaining operator
const user = {
firstName: 'John',
lastName: 'Doe',
address: {
street: '123 Anywhere Lane',
city: 'Some Town',
state: 'NY',
zip: 12345,
},
}
const street = user && user.address && user.address.street
// '123 Anywhere Lane'
const badProp = user && user.fakeProp && user.fakeProp.fakePropChild
// undefined
@mariusa
Copy link

mariusa commented Apr 15, 2020

user.fakePropChild

should be user.fakeProp.child , to actually be a child & similar with user.address.street ?

@thawkin3
Copy link
Author

thawkin3 commented Apr 15, 2020

Thank you! I've corrected it now to be:

const badProp = user && user.fakeProp && user.fakeProp.fakePropChild

Now it matches up with the corresponding optional chaining operator gist: https://gist.github.com/thawkin3/91e89ad6e1963a4f0bc4a40c2d19d03d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment