Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep Javascript check if undefined without TypeError

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?

like image 377
luchaninov Avatar asked Aug 11 '11 11:08

luchaninov


1 Answers

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.

like image 174
Baz1nga Avatar answered Oct 07 '22 00:10

Baz1nga