/ JAVASCRIPT, FRONT-END

How to solve [cannot read property bar of undefined] in Javascript?

Question

I have a property of an Obejct, like profile.user.name.lastName, but somethings, name is undefined, so there is no way to access profile.user.name.lastName, the error message will be:

Uncaught TypeError: Cannot read property 'name' of undefined

Answer

Just need to check for profile.user.name, if it exists, pass the name value. Using ternary conditional operator to solve this issue.

profile.user.name ? profile.user.name.lastName : undefined

Reference


This is the end of post