Existential Operator / Null Propagation Operator

Sander Deryckere sanderd17 at gmail.com
Tue Jun 2 10:09:06 UTC 2015


(I hope this arrives in the right thread, it's meant as a reply for
https://esdiscuss.org/topic/existential-operator-null-propagation-operator )

I very much like the proposal, our JS code is full with cases where certain
components can be null, but we need to execute an action with the component
when it's not null.

However, the collisions with existing syntax is indeed troublesome. So far,
I liked the `?.`, `?[` and `?(` operators the most.

But what should be done with cases like `obj?[1]?[2]:[3]`. Does it test
`obj?[1]` and returns `[2]` or `[3]` depending on the result, or does it
test `obj` and return `[1]?[2]` or `[3]` depending on the result.

A similar case with functions: `func1?(func2)?(func3):(func4)`. Does it
test `func1?(func2)`, or can it return `(func2)?(func3)`?

Both cases depend on the binding to the `:` of the ternary operator. Which
might cause too many changes to the spec, and too many exceptions to keep
the language compatible.

The `.?` operator seems to have no alternative for variable keys
(`obj[key]`), which is IMO the most usefull use-case (testing explicitly
for null is most likely to happen when you don't know a lot about the
object when writing the code, so likely you also don't know the key). As
such `.?` isn't an option for me.

For the prefix operator, it's unclear to me how you would do the following:
Say you know `obj` is non-null, you want to test if it has a key `k1`, but
if `k1` exists, you know it will also have a key `k2` a level deeper. With
the suffix operator, this would be `obj[k1]?[k2]`, but with the prefix
operator, it could be `obj?[k1][k2]` (which again has the same problems as
first described with the `?[` operator), while it could also be
`obj[?k1][k2]` (which even conflicts with itself, as it could also test if
`k1` as a variable is non-null).

As such, all these proposals have at least as many issues as `?.`. And `?.`
already has too many issues to implement it.

So, I'd like to propose another operator: `??` (with `??[` and `??(`)

In current syntax, the `?` is only used for the ternary operator, and
requires something else before and after it. Which means that any code that
has `??` is currently invalid.

We currently sometimes use the logical && to test nullness of a value, and
access its properties. Like:

`var result = obj && obj.key;`

Which tests if `obj` exists (assuming obj is an object when defined), and
returns `obj.key` if it does. With the `??` operator, it can be simplified
to

`var result = obj??key;`

Combined with `arr??[idx]` and `func??(arg)`, I think this will work very
fine.

Regards,
Sander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150602/9e17a0ce/attachment.html>


More information about the es-discuss mailing list