Optional Chaining (aka Existential Operator, Null Propagation)

Claude Pache claude.pache at gmail.com
Fri Feb 5 17:45:57 UTC 2016


> Le 5 févr. 2016 à 16:22, Kevin Smith <zenparsing at gmail.com> a écrit :
> 
> Yes: the `?.` operator does not change the meaning of the subsequent `.` operator. I like to think of it as: the effect is local (short-circuiting aside), you are not switching between "modes". It’s a feature.
> 
> Just curious:  what's the rationale for that behavior, as opposed to "deep" short-circuiting?  It seems like if I have a long query, like:
> 
> a.b.c.d
> 
> I think I would typically want to test that the whole query is satisfiable (not just a single term), so I'll need to write:
> 
> a?.b?.c?.d
> 


(In order to avoid confusion from those that read casually that thread, I recall that the proposal already features "long" short-circuiting in the sense that the end point of the short-circuiting jump is the end of the entire chain of property accesses, method calls, etc. The issue here is essentially whether a `?.` should implicitly transform all subsequent `.` in the chain into `?.`.)

The general rationale is, as I've said, no modes, because modes are confusing. In the particular case, there should be testimonies that the pattern `a?.b?.c?.d` is both sufficiently common and annoying in order to consider an exception to that rule.

But here is a random example, where I would not use stacked `?.` or something semantically equivalent:

```js
var numberOfSelectedItems = myForm.querySelector('select[name=foo]')?.selectedOptions.length || 0;
```

In case `myForm.querySelector('select[name=foo]')` is not null, then `myForm.querySelector('select[name=foo]').selectedOptions` is always an HTMLCollection and has always a `length` property. If it is not the case, then either I made a typo, or I am testing some ancient browser that doesn’t support yet the `selectedOptions` property. In both cases, I want an exception to be thrown rather than an error to be dropped: it's easier to debug.

—Claude


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160205/c4a2f7c4/attachment.html>


More information about the es-discuss mailing list