tc39 / proposal-optional-chaining

https://tc39.github.io/proposal-optional-chaining/
4.94k stars 75 forks source link

A proposal that enables .? and ?[] #81

Closed Mouvedia closed 5 years ago

Mouvedia commented 5 years ago

This is inspired by #77.

/*** USE CASES ***/

// optional static property access
catch a?.b;

// optional dynamic property access
var qux = 'foo-bar'

catch a?[qux];

// optional function/method call
catch mayBeNullOrUndefined?(...args);

/*** TRANSPILATION ***/

catch a?.b;
// equivalent of
a == null ? undefined : a.b;

PROS

CONS

claudepache commented 5 years ago

As already said somewhere else, Optional chaining is not about discarding errors, and using the keyword ”catch” will maintain the confusion. For example, arguments?.callee will throw a TypeError if triggered inside a strict-mode function.


  • short (subjective)

I disagree, catch x?[y] is significantly longer than x?.[y]


Also: Con: Using a keyword just for enabling syntax is a precedent (and imho not a good precedent). (In the past, "use strict" was intended to be mandatory for having new features, but later, it was decided that new features should be available also in sloppy mode.)

Mouvedia commented 5 years ago

For example, arguments?.callee will throw a TypeError if triggered inside a strict-mode function.

By discards the error I meant discards the error that you are expecting. Obviously any other error would throw normally.

I disagree, catch x?[y] is significantly longer than x?.[y]

Like I said it's better for clarity: it's explicit. And I consider ?.[] an atrocity. Also ?.[] is not consistent with ?. as explained numerous times in other issues.

claudepache commented 5 years ago

By discards the error I meant discards the error that you are expecting. Obviously any other error would throw normally.

Sure, you meant that. But what is obvious for you is not obvious for the lambda programmer. It is not clear why a catch keyword prefixing an expression discards only one specific error that would occur in one specific case when evaluating that expression.

obedm503 commented 5 years ago

Maybe instead of using catch a different keyword could be used. catch already has meaning of catching all errors. maybe a keyword could help us get away from ?.[ and ?.()

ljharb commented 5 years ago

As well as the reasons already stated, it must be possible to do something like a.b.c.d where the .b and .d are optional but the .c is not.

a?.b.c?.d, for example, provides this - how would you do it with your suggestion?

Mouvedia commented 5 years ago

a?.b.c?.d, for example, provides this - how would you do it with your suggestion?


catch a?.b.c?.d;
Mouvedia commented 5 years ago

It is not clear why a catch keyword prefixing an expression discards only one specific error that would occur in one specific case when evaluating that expression.