1

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.

2 Answers 2

1

After you parse the JSON, you can fill in the object with default values:

fields = ['first_name', 'last_name', 'job_title'];
for (var i = 0; i < fields.length; i++) {
    if (!(fields[i] in object)) {
        fields[i] = '';
    }
}

Another option would be to write your own getProp function:

function getProp(obj, property, default) {
    if (property in obj) {
        return obj[property];
    } else {
        return default;
    }
}

Then use getProp(obj, 'job_title', '') instead of obj.job_title.

This could be rewritten with try/catch, it might be more efficient that way:

function getProp(obj, property, default) {
    try {
        return obj[property];
    } catch (e) {
        return default;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

that would require me copying my whole API's data structure into my clientside... not sure this is a good idea.
I actually like your second option quite a bit. I was already doing something vaguely similar... though abstracting the variable existence verification is a nice idea. In essence, this "could" be done with the try-catch blocks too, I suppose?
Yes, I've added that version.
lookin good! I'll do some benchmarks on my end to see what works fastest, but this is very much along the lines of what I needed! thx.
obj[property] will not throw if obj has no property.
1

You're looking for exception handling:

try {
  // Do something that can throw an exception
} catch(err) {
  console.log('the error was ' + err);
  // set a default value, or whatever
}

This is exactly what exceptions are designed for (gracefully handling errors in a program and continuing smoothly). If you want to catch the undefined variable and set it to a default value:

catch(e if e instanceof TypeError){
    if ( /'/.test( err.message ) ){
        prop = err.message.match( /'(.*?)'/ )[1];
        obj['wasundefined'] = {}
        obj['wasundefined'][prop] = "my value";
    }
}

This works because the error message for TypeError follows the pattern: TypeError: Cannot read property 'c' of undefined

11 Comments

Good god, I guess my coffee didn't kick in yet... Thx for this, it quite obviously is the way to go.
He doesn't want to report the error, he wants it to use a default value instead of signalling an error.
@Barmar, couldn'T I tell the catch block to return my empty string?
You would have to put that around EVERY use of the variable.
@SebastienD. Not if you're doing it on the string TypeError: Cannot read property 'c' of undefined. You could also split on ' and pull out the middle entry, ie err.message.split("'")[1]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.