Test if something is not undefined in JavaScript

Test if something is not undefined in JavaScript

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

Uncaught TypeError: Cannot read property ‘title’ of undefined.

Solutions/Answers:

Solution 1:

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
}

Solution 2:

Just check if response[0] is undefined:

if(response[0] !== undefined) { ... }

If you still need to explicitly check the title, do so after the initial check:

if(response[0] !== undefined && response[0].title !== undefined){ ... }

Solution 3:

I had trouble with all of the other code examples above. In Chrome, this was the condition that worked for me:

typeof possiblyUndefinedVariable !== "undefined"

I will have to test that in other browsers and see how things go I suppose.

Solution 4:

Actually you must surround it with an Try/Catch block so your code won’t stop from working.
Like this:

try{
    if(typeof response[0].title !== 'undefined') {
        doSomething();
    }
  }catch(e){
    console.log('responde[0].title is undefined'); 
  }

Solution 5:

typeof:

var foo;
if (typeof foo == "undefined"){
  //do stuff
}

Solution 6:

It’ll be because response[0] itself is undefined.

Related:  Javascript Regexp - Match Characters after a certain phrase