Existential operator

Dmitry A. Soshnikov dmitry.soshnikov at gmail.com
Wed Apr 13 02:37:35 PDT 2011


(I separate it from recent thread on shared handlers for proxies).

The existential operator is a syntactic sugar to avoid long testing 
whether a property exists and only after that to apply it. This already 
is again used in CoffeeScript, so I'll show the examples:

let street = user.address?.street

which desugars e.g. into:

street = (typeof user.address != "undefined" && user.address != null)
     ? user.address.street
     : undefined;

The same with functions (which is even more convenient that just with 

let value = entity.getBounds?().direction?.x

which desugars into:

let x = (typeof entity.getBounds == "function")
     ? (typeof entity.getBounds().direction != "undefined" && 
entity.getBounds().direction != null)
         ? entity.getBounds().direction.x
         : undefined

(I specially avoid optimization with saving intermediate results -- just 
to keep clarity)

I think it's useful thing and I already used in several times. Do we 
need it in ES6? It's convenient.

Another examples (which already as I know were planed for ES6, such as 
||= or  ?=, etc):

score ?= 0

desugars into (notice, there's no unnecessary assignment as in score = 
score || 0; also, this sugar assumes that `score` may not even exists):

(typeof score != "undefined" && score != null) : score ? (score = 0);

Normally, it can be done (assuming that `score` exists):

score || (score = 0);

so score ?= 0 is really just a sugar, no more, no less.


More information about the es-discuss mailing list