I thought I had correctly followed the recommendations in this question for checking undefined:
if(typeof window.session.location.address.city != "undefined")
console.log(window.session.location.address.city);
But the code above generates this error:
Uncaught TypeError: Cannot read property 'city' of undefined
What’s the correct way to perform this check?
Check for the existence of each property:
That may log
undefined, but will not result in an error. If you only want to logcityif it is notundefined, just add in a&& typeof session.location.address.city != "undefined". We usetypeofin this case because ifcitycontains an empty string ornull, it will also evaluate tofalse(ie, it is “falsey”). Of course, if you only want to logcityif it has a value, leave off thetypeofand just check to see if it evaluates totrue(ie, it is “truthy”) the same way as the others.