The "problem" that I have from time to time is that I have an object, for example, user = {} and when using the application this is filled. Say somewhere after an AJAX call or something that I do this:
user.loc = { lat: 50, long: 9 }
Elsewhere I want to check if user.loc.lat .
if (user.loc.lat) { // do something }
If it does not exist, it will result in an error. If user.loc.lat not undefined , user.loc course also not undefined .
"Cannot read property 'lat' of null" - Dev Tools error
This means that I need to check it like this:
if (user.loc) { if (user.loc.lat) { // do something } }
or
if (user.loc && user.loc.lat) { // do something }
It's not very pretty, and the larger my objects, the worse it gets - obviously (imagine 10 levels of nesting). It seems to me that if(user.loc.lat) does not just return false if user.loc not undefined .
What is the ideal way to check such situations?
javascript object javascript-objects
ProblemsOfSumit May 22 '14 at 13:55 2014-05-22 13:55
source share