2

I dont know if a.b is set. I want to do something only if a.b[0].c is true. I can do something like this:

if (a.b && a.b[0] && a.b[0].c) {
    // ...
}

Is there a shortcut to check nested existence? Can I simplify this kind of condition?

rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • I think this is the clearest and most concise way to do what you want. And this is why I love coffeescript so much. In CS you just say `if a?.b?[0]?.c then ...`. I really hope future versions of javascript incorporate more of the simplicities of coffeescript. – jusopi Jan 20 '17 at 16:44

1 Answers1

3

I used to code golf, and one of the tricks we used is the following.

(myArray || [])[0] || 0

First, myArray || [] is evaluated, if myArray exists, this returns it, if it doesn't, then it returns an empty array. Let's say myArray isn't defined. Next, the [][0] || 0 expression gets evaluated ans because [][0] is undefined, this returns 0.

In your case it could be used the following way:

((a.b || [])[0] || {}).c || {}

This returns an empty object if something's undefined.

I'm not saying you should use this (in fact, you shouldn't), I just want to show you, that there is a smaller solution.

Update:

If tc39 gets through, then you'll have a much better solution using optional chaining:

a.b?[0]?.c
Bálint
  • 4,009
  • 2
  • 16
  • 27