Optional chaining skip nested object next levels

I wish optional chaining (?.) have a better design.
Currently needs ({a: {}}).a?.b?.c?.d?.() in order not to fall into a code exception.

Instead, if obj.a.b doesn't exist, I propose ({a: {}}).a?.b.c.d() to be enough - skip nested object next levels if found obj.a.b as not existing.

ref https://github.com/tc39/proposals/issues/398

That was explicitly rejected during the optional chaining proposal - because it would prevent people who WANT an exception.

The intention is for the ?. to explicitly mark each place where something might be nullish - it's not to avoid exceptions, it's to simplify the places where you want the short-circuiting behavior. It's optional chaining, not "safe navigation".

1 Like

In your specific example, you really only need ({a: {}}).a.b?.c.d() to be safe from exceptions. And I think that's the beauty of how optional chaining is currently designed, it shows exactly where you expect a nullish value to be, and everywhere else you're indicating that you don't expect a nullish to ever show up there.
I'd also point out that, if a need does come to use ?. a lot in the same expression, it's not that verbose to do - after all, some languages' property access operator is two characters long by default (->).

It wouldn’t be quite the same but a try expression would be one possible way to have a safe nested access