[javascript] JavaScript "cannot read property "bar" of undefined

I've got a function that takes 3 parameters. The problem I have is one of the parameters is a property of a sometimes undefined value of an Object (i.e. it takes in thing.foo.bar, and sometimes thing.foo is undefined, so it can't access bar).

What's a way around this? Within the function's declaration, I have a conditional checking: if (!parameterName), but the browser (Chrome) is still throwing an error that it can't read the bar property of undefined.

This question is related to javascript undefined

The answer is


Compound checking:

   if (thing.foo && thing.foo.bar) {
      ... thing.foor.bar exists;
   }

Just check for it before you pass to your function. So you would pass:

thing.foo ? thing.foo.bar : undefined

You can safeguard yourself either of these two ways:

function myFunc(thing) {
    if (thing && thing.foo && thing.foo.bar) {
        // safe to use thing.foo.bar here
    }
}

function myFunc(thing) {
    try {
        var x = thing.foo.bar;
        // do something with x
    } catch(e) {
        // do whatever you want when thing.foo.bar didn't work
    }
}

In the first example, you explicitly check all the possible elements of the variable you're referencing to make sure it's safe before using it so you don't get any unplanned reference exceptions.

In the second example, you just put an exception handler around it. You just access thing.foo.bar assuming it exists. If it does exist, then the code runs normally. If it doesn't exist, then it will throw an exception which you will catch and ignore. The end result is the same. If thing.foo.bar exists, your code using it executes. If it doesn't exist that code does not execute. In all cases, the function runs normally.

The if statement is faster to execute. The exception can be simpler to code and use in complex cases where there may be many possible things to protect against and your code is structured so that throwing an exception and handling it is a clean way to skip execution when some piece of data does not exist. Exceptions are a bit slower when the exception is thrown.