kritop
kritop

Reputation: 607

Uncaught TypeError even if typeof is used in if clause

$.each(res.data,function(idx,val){
if (typeof val.location.longitude != 'undefined') {
 console.log(val.name + ':' + val.location.latitude + ', ' + val.location.longitude);
}

why is this still true and returns

Uncaught TypeError: Cannot read property 'longitude' of undefined 

even if longitude is not defined?

Upvotes: 0

Views: 49

Answers (1)

Pointy
Pointy

Reputation: 413712

You're checking the wrong thing:

if (typeof val.location != 'undefined')
  // ...

The error message is telling you that val.location is undefined, not that the "longitude" property is undefined. It's, "Hello I cannot read the value of a property called 'longitude' from something whose value is undefined", in other words.

Upvotes: 4

Related Questions