Proposal: Selector/Select Expression
simonfarrugia26 at gmail.com
Sun Jun 23 10:43:20 UTC 2019
I was expecting that someone brings up the brackets property accessor at some point.
I would argue that there is a bit of syntactic inconsistency since usually when using the bracket accessors it is not preceded by a dot.
const getEmail = user => user["contacts"].email; // No dot between user & ["contacts"].
const getEmail = .["contacts"].email;
Having said that, the currently proposed Optional Chaining operator (Stage 2) does exactly that and more:
obj?.prop // optional static property access
obj?.[expr] // optional dynamic property access
func?.(...args) // optional function or method call
So I'd say that there is consistency with what is currently being proposed.
Regarding the Optional Chaining operator, which precedes the dot. How would that work?
It would have to be something like this, if allowed.
const getEmail = user => user?.contacts.email;
const getEmail = ?.contacts.email;
It does look odd at first, but it’s quite simple is you think about it. We are just omitting the initial part of the expression.
More Examples with Optional Chaining operator:
// With optional dynamic property access.
const getUserEmail = user => user?.["contacts"].email;
const getUserEmail = ?.["contacts"].email;
// With optional function or method call.
const getJohnsEmail = getUserContacts => getUserContacts?.("John").email;
const getJohnsEmail = ?.("john").email;
The beauty of what is being proposed is that there is nothing new to learn or any new weird operator introduced.
Any weirdness one might find with the expressions above will already have been introduced by the Optional Chaining operator.
The only thing this does is to allow you to omit the initial (redundant) part of the expression.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the es-discuss