Deep Javascript check if undefined without TypeError
Asked Answered
D

4

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?

Dactylology answered 11/8, 2011 at 11:5 Comment(4)
possible duplicate of javascript test for existence of nested object keyEster
i have tested your code it is working, in which browser you are getting error? could you also post your FooLatisha
just run this in your console.. "typeof abc.xyz" it will throw an error!Figurine
@aamir, there is no error in this code, question was about the complex if statement and how to aviodUpheaval
F
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.

Figurine answered 11/8, 2011 at 11:14 Comment(0)
D
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.

Dinar answered 11/6, 2018 at 19:34 Comment(0)
C
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') {...}
Cardenas answered 11/2, 2020 at 15:46 Comment(0)
C
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

Cheetah answered 11/8, 2011 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.