hypermiler
hypermiler

Reputation: 2107

Catching undefined javascript variable

I'm using Ajax/jsonp to access a remote database. As such, the response.error is never returned. I'm trying to catch an instance when the remote server does not return data for whatever reason. I've tried everything I can think of to catch an undefined condition and I can't seem to catch it. I've tried to find the variable with Firebug. I've tried using just about every combination of the following code I can think of and just can't seem to get it to work.

                      if ( typeof(data.flightStatuses[0].operationalTimes.publishedDeparture.dateLocal) === "undefined") {
                        alert("flightstats is undefined");
                    }

Any ideas greatly appreciated!!!!

I also tried:

                      if ( typeof data.flightStatuses === "undefined") {
                        alert("flightstats is undefined");
                    }

Above code won't execute alert either....

FINALLY! This worked...

if ( typeof data.flightStatuses[0] === "undefined")

I don't really know why, but it did. thanks your everyone's help!

Upvotes: 4

Views: 6666

Answers (3)

jbiz
jbiz

Reputation: 414

This seems to work

   try {
        dateLocal = typeof (data.flightStatuses[0].operationalTimes.publishedDeparture.dateLocal) !== 'undefined';
        if (dateLocal) {
            // Do something with dateLocal
            // ...
        }
    }
    catch (err) {
        alert("flightstats is undefined: " + err);
    }

Upvotes: 2

Ronnie
Ronnie

Reputation: 1079

Could this work?

if (data.flightStatuses[0].operationalTimes.publishedDeparture.dateLocal) === null) {
                        alert("flightstats is undefined");
                    }

Upvotes: 0

Paul
Paul

Reputation: 141829

If data.flightStatuses is undefined, then data.flightStatuses[0] will throw an error. Make you only check if the relevant identifier is undefined:

if(typeof data.flightStatuses === "undefined") {
    alert("flightStatuses is undefined");
} else {
    // Here you know data.flightStatuses exists, so you can test data.flightStatuses[0]
    if(typeof data.flightStatuses[0] === 'undefined'){
        alert("flightStatuses[0] is undefined");
    } else {
        // And so on, depending on how much you know about your data source
    }
}

Upvotes: 2

Related Questions