Test if something is not undefined in JavaScript

Raimonds picture Raimonds · Aug 12, 2011 · Viewed 284.8k times · Source

I'm checking if(response[0].title !== undefined), but I get the error:

Uncaught TypeError: Cannot read property 'title' of undefined.

Answer

amosrivera picture amosrivera · Aug 12, 2011

response[0] is not defined, check if it is defined and then check for its property title.

if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
    //Do something
}