Closed phaux closed 3 years ago
Looks like babel implements option 2.
Looks like babel implements option 2.
Note that this is not intended. Probably it would be better to throw an error until it's decided.
In general I would expect foo?.bar(?)
to return undefined
if foo
is null/undefined
, rather than deferring evaluation. The reason is that partial application eagerly evaluates non-placeholder arguments, i.e., foo.bar(++i, ?)
would eagerly evaluate the pre-increment ++i
. However, arguments in an optional chain are not evaluated if the root of the chain is null/undefined
, i.e., foo?.bar(++i, x)
would not evaluate the pre-increment ++i
.
The only option to remain consistent would be Option 2.
Since optional chaining is reaching stage-3, I thought it would be worth discussing how that syntax interacts with partial application. Currently it's a syntax error in babel AFAIK.
Example:
Option 1
fn
is a function which either does nothing iffoo
was nullish or in other case works normally. This would be equivalent to:The question is if it should also work like that with
foo?.bar(?)
(maybe) andfoo?.bar.baz(?)
(probably not)Option 2
fn
is undefined iffoo
was nullish. Equivalent to:It would work the same way no matter how deep in the chain which is less surprising. E.g.
foo?.bar.baz(?)
would be undefined iffoo
was nullish. We can then use the resulting maybe-function likefn?.(x)
.Motivating example
Supporting this syntax would be beneficial in some situations.
This example would work pretty much the same way with both options.