r/javascript • • Feb 20 '18

Optional Chaining may be coming to JavaScript

https://dev.to/sammyisa/optional-chaining-may-be-coming-to-javascript--4ff0
321 Upvotes

100 comments sorted by

View all comments

1

u/Bluecewe Feb 20 '18 edited Feb 20 '18

The dot notation is great (object?.property). However, it seems a little strange for bracket notation (object?.['property']) and function invocation (exampleFunction?.(argument)). Indeed, if you were to drop the ? in either, and run it in JavaScript today, an exception would be thrown.

I'd have hoped that JavaScript engines could handle brackets and functions with only the ?, allowing these three forms:

object?.property;
object?['property'];
exampleFunction?(argument);

The proposal authors have briefly justified this in their FAQs:

We don’t use the obj?[expr] and func?(arg) syntax, because of the difficulty for the parser to distinguish efficiently those forms from the conditional operator, e.g. obj?[expr].filter(fun):0 and func?(x - 2) + 3 :1.

Hopefully this difficulty can be overcome for the final standard. There's a lot of discussion about this in the proposal repository. It would be nice to avoid awkward syntax like the current proposal.

1

u/palparepa Feb 20 '18

I don't think they mean "difficult" as in difficult for the parser, but for the programmer of the parser.

Perl 6 solved this by changing the conditional operator to ?? ::

1

u/Bluecewe Feb 20 '18

That's possible. I assumed it was for performance reasons because they used the term 'efficiently'. Perhaps, as you suggest, they mean 'efficient to implement', meaning it's simple to implement.