Deep Javascript check if undefined without TypeError

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') {...}

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.


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.