I always face a situation where I need to check the existence of a specific property before doing something with it, like :
if (this.foo & this.foo.bar){ //first to make sure the `this.foo` is not undefined or null, then read the property `bar`
// do something with the `this.foo.bar`
}
This kind of checking is used quite often in ReactJS when we need to generate a list of data, like :
{
this.state.list && this.state.list.map(element => ... )
}
However, if the target property is nested deep inside four or five level, like :
this.foo.bar.baz.qux
And the checking process will be quite verbose :
if(this.foo && this.foo.bar && this.foo.bar.baz && this.foo.bar.baz.qux){
// do something with `this.foo.bar.baz.qux`
}
I know the main purpose of checking is to make sure that we do not get the error:
Cannot read property qux of undefined (or null)
Is there another approach? I'm looking for a shorter way, like :
qux
inthis.foo
Any thoughts would be appreciated.
Thanks in advance.