Search code examples
javascript

How can I avoid 'cannot read property of undefined' errors?


In my code, I deal with an array that has some entries with many objects nested inside one another, whereas some do not. It looks something like the following:

// Where this array is hundreds of entries long, with a mix
// of the two examples given
var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];

This is giving me problems, because I need to iterate through the array at times, and the inconsistency is throwing me errors like so:

for (i=0; i<test.length; i++) {
    // OK, on i==0, but 'cannot read property of undefined' on i==1
    console.log(a.b.c);
}

I am aware that I can say if(a.b){ console.log(a.b.c)}, but this is extraordinarily tedious in cases where there are up to 5 or 6 objects nested within one another. Is there any other (easier) way that I can have it only do the console.log if it exists, but without throwing an error?


Solution

  • Update:

    • If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
    • TypeScript has added support for optional chaining in version 3.7.
    // use it like this
    obj?.a?.lot?.of?.properties
    

    Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7:

    A quick workaround is using a try/catch helper function with ES6 arrow function:

    function getSafe(fn, defaultVal) {
      try {
        return fn();
      } catch (e) {
        return defaultVal;
      }
    }
    
    // use it like this
    console.log(getSafe(() => obj.a.lot.of.properties));
    
    // or add an optional default value
    console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));