Existential Operator / Null Propagation Operator

Christoph Pojer christoph.pojer at gmail.com
Mon Apr 6 18:33:59 UTC 2015

Tim Yung and I have hacked on a reference implementation for the
"Existential Operator" using esprima-fb and jstransform: "a?.b"


`a?.b` => `(a == null ? void 0 : a.b)`
`a?.b.c` => `(a == null ? void 0 : a.b.c)`

This must also make sure that `a` only gets evaluated a single time.

Based on previous discussions on es-discuss and TC39, it seems that
this was tabled for ES6. I think now is a good time to bring it up for
ES7. There is precendence for this feature in other languages - it was
recently added to C# and Hack and has always been in CoffeeScript.
TypeScript is waiting for TC39:

In the past, this topic has invited a lot of bikeshedding, but I'd
like us to look past this. Several communities within and outside the
JS community have identified the need for this operator. My
understanding is that a decision needs to be made about whether the
operator should short-circuit additional invocations in the call chain
if the operand is null (aka. null propagation).

For example, if `a` is null, should `a?.b.c`:

1) evaluate to `(void 0).c` and throw a TypeError?
2) short-circuit at `a` and return `void 0`?

It appears that C# chose option #2 whereas Hack and CoffeeScript chose
option #1. Our current implementation chose option #1 but we'd be
happy to build a reference implementation for option #2.

I recall that another issue was that of transitivity. Right now,
(a.b).c and a.b.c are equivalent. (a?.b).c and a?.b.c would not be
equivalent expressions. I think we need some input from the people on
this list about whether this is okay or why we value transitivity for
this operator.

If we can come to an agreement on the existential operator for member
expressions, we would also be setting a precedent for other features
of the same family. For example, existential call expressions: `fn?()`
which would conditionally invoke `fn`.

esprima-fb change: https://github.com/cpojer/esprima/tree/existential-operator
jstransform change:

Previous discussions on es-discuss:
* https://esdiscuss.org/topic/the-existential-operator
* https://esdiscuss.org/topic/specifying-the-existential-operator-using-abrupt-completion
* https://esdiscuss.org/topic/sept-18-tc39-meeting-notes

Christoph Pojer

More information about the es-discuss mailing list