I'm parsing some data that I fetched, but some of the data in the JSON is not defined.
For example, a contact object can have first_name, last_name, and job_title, but sometimes job_title is not set.
To avoid my scripts crashing because of this undefined variable, I check to make sure the variable exists:
if (this.data[x]) {
// do your thing
}
I have to put these checks all over the place and, on particularly large scripts, it makes my code difficult to follow.
Is there a better way to tell my code to keep running even if it hits an undefined variable? For example, if an undefined value is met anywhere in the path, return an empty string.
Below is an example of a situation where this would be helpful because I could cut back on all the ifs:
var filtrate;
if (d.ContactValues) {
filtrate = d.ContactValues.filter(function(o) {
return o.RefContactMethod.key === 'office_phone';
});
if (filtrate.length > 0) {
return filtrate[0].value;
}
//... additional if statements ...
}
EDIT #1
Just to keep you all posted, I ran some basic performance tests: http://jsperf.com/undefined-var-try-catch-and-other
I will run a more in-depth and real-world tests later today.