Search code examples
javascriptoptional-chaining

In JavaScript, is there an easier way to check if a property of a property exists?


Is there an easy way to natively determine if a deep property exists within an object in JavaScript? For example, I need to access a property like this:

var myVal = appData.foo.bar.setting;

But there is a chance that either foo, foo.bar, or foo.bar.setting has not been defined yet. In Groovy, we can do something like this:

def myVal = appData?.foo?.bar?.setting

Is there a similar way to do this in JavaScript, without having to write a custom function or nested if statements? I've found this answer to be useful, but was hoping there was a more elegant and less custom way.


Solution

  • The optional chaining operator (?.) was introduced in ES2020. Now, you should be able to write:

    const myVal = appData?.foo?.bar?.setting