Milkmate
Milkmate

Reputation: 109

Not sure what's wrong with this JavaScript "undefined" check

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?

Upvotes: 1

Views: 177

Answers (3)

gilly3
gilly3

Reputation: 91497

Check for the existence of each property:

if (window.session && session.location && session.location.address)
    console.log(session.location.address.city);

That may log undefined, but will not result in an error. If you only want to log city if it is not undefined, just add in a && typeof session.location.address.city != "undefined". We use typeof in this case because if city contains an empty string or null, it will also evaluate to false (ie, it is "falsey"). Of course, if you only want to log city if it has a value, leave off the typeof and just check to see if it evaluates to true (ie, it is "truthy") the same way as the others.

Upvotes: 2

doogle
doogle

Reputation: 3406

if(typeof window.session.location.address === 'undefined')
    alert("address is undefined!");
else
    console.log(window.session.location.address.city);

Upvotes: 0

canon
canon

Reputation: 41675

address is undefined so you can't read its property city

You'll have to check that address is defined first.

Upvotes: 4

Related Questions