11

I'm tired to write something like

if (
  typeof Foo != 'undefined' &&
  typeof Foo.bar != 'undefined' &&
  typeof Foo.bar.baz != 'undefined' &&
  Foo.bar.baz == 'qux'
) {...}

In PHP it's a little bit better:

if (!empty($foo['bar']['baz']) && $foo['bar']['baz'] == 'qux') {...}

Ideally it would be:

function u(value) {
    return (typeof value != 'undefined') ? value:null;
}
if (u(Foo.bar.baz) == 'qux') {...}

But browser shows "TypeError" when I try to do this. Is there any way to make "u" function?

4
  • 3
    possible duplicate of javascript test for existence of nested object key Commented Aug 11, 2011 at 11:08
  • i have tested your code it is working, in which browser you are getting error? could you also post your Foo
    – Aamir Rind
    Commented Aug 11, 2011 at 11:20
  • just run this in your console.. "typeof abc.xyz" it will throw an error!
    – Baz1nga
    Commented Aug 11, 2011 at 11:32
  • 1
    @aamir, there is no error in this code, question was about the complex if statement and how to aviod Commented Aug 11, 2011 at 12:16

4 Answers 4

7

April 2020 Update

As of Node.JS version 14, you can now use the following syntax for "optional chaining"

if(foo?.bar?.obj?.prop1)

If any of the chained properties don't exist, then the value will be typed "undefined".

https://v8.dev/features/optional-chaining


Original reply:

You don't have to state the undefined explicitly. The check can be something like:

if(foo && foo.bar && foo.bar.obj && foo.bar.obj.prop1)

Or you can have a try catch block to catch if there is any error:

try
{
  if(foo && foo.bar && foo.bar.obj && foo.bar.obj.prop1)
    {}
}
catch(e)
{
 alert(e);
}

But yes I can see the problem. I would suggest to try and avoid deep nesting like you have.

3

To solve this problem I use Lodash _.get.

if(_.get(Foo, ['bar','baz'] === 'qux') doThings()

If Foo.bar or Foo.bar.baz are undefined, you will not get a type error, and it's quite a bit easier to read and debug.

2

There is a new optional chaining operator in JavaScript. As of 2020 it is working only in the newest version of the popular browsers. So I recommend using it only with transpilers.

if (Foo && Foo?.bar?.baz == 'qux') {...}
0

As you assume that every steps in your chain is an object and not 0, "" or boolean false you can write:

if (
 Foo  &&
 Foo.bar &&
 Foo.bar.baz &&
 Foo.bar.baz == 'qux'
) {...}

But after all its better not to have such deep nested objects

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.