To access any property of this user object, you could simply do things like:
What happens when you try to access a property on the object that doesn’t exist?
Nothing too terrible right? If the property doesn’t exist on the object,
undefined will be returned as the value. Now what happens if you try to access a property two, three, or more levels deep, where both levels don’t exist?
Bad things happen, horrible things, things you don’t want to see! The severity of what happens varies greatly depending on the context of where the attempt to access the property is happening. This type of error can be pretty bad because it often leads to infinite loops, frozen apps, bad data, or just silent failures that lead to who knows what down the line. There are some things we can do though to protect ourselves against nasty bugs like this. You may find it redundant or an unnecessary to add an extra step, but you’re really going to save yourself some time and headache in the long run by being proactive about accessing object properties safely. A tried and true method for accessing nested object properties safely is to simply check for the existence of a property before trying to do anything with it. For example, you could use a simple if statement:
First, we’re importing Lodash from NPM. We can access the different methods of Lodash by using the_ character. In the get method, the first argument is the object you want to access, the second argument is a string of the path you want to access, and the third argument is a default value to return. The default value you set in the third argument will be returned if Lodash is unsuccessful in finding a value at the path you’ve given. If you do not set a default value like the last line in our example, that is ok too because get will return undefined for you by default. For more examples, see the documentation at https://lodash.com/docs/4.17.4#get. As a general rule of thumb, I will use Lodash get when I need to access a property in an object that is more than one level deep. It can be useful to use get when searching the first level if you want to return a default value that is something other than undefined though.
That’s it for this bit on object properties. Let me know what you think or if you have any questions in the comments.