44

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Connor
  • 4,138
  • 8
  • 34
  • 51

4 Answers4

52

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • @Mörre: This works just fine. OP explicitly states that `thing.foo` is undefined, so it _has_ to be declared. – Cerbrus Dec 10 '14 at 08:18
11

Compound checking:

   if (thing.foo && thing.foo.bar) {
      ... thing.foor.bar exists;
   }
Marc B
  • 356,200
  • 43
  • 426
  • 500
9

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
8

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

thing.foo ? thing.foo.bar : undefined
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95