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?

luchaninov
  • 6,792
  • 6
  • 60
  • 75
  • 3
    possible duplicate of [javascript test for existence of nested object key](http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) – Felix Kling Aug 11 '11 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 Aug 11 '11 at 11:20
  • just run this in your console.. "typeof abc.xyz" it will throw an error! – Baz1nga Aug 11 '11 at 11:32
  • 1
    @aamir, there is no error in this code, question was about the complex if statement and how to aviod – Andreas Köberle Aug 11 '11 at 12:16

4 Answers4

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.

drj
  • 533
  • 2
  • 16
Baz1nga
  • 15,485
  • 3
  • 35
  • 61
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.

drj
  • 533
  • 2
  • 16
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') {...}
Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36
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

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297