On 13.04.2011 16:57, Brendan Eich wrote:
See http://wiki.ecmascript.org/doku.php?id=strawman:default_operator -- the
proposal there is ?? and ??= since single ? is ambiguous after an expression
due to conditional expressions (?:).
On Apr 13, 2011, at 11:37 AM, Dmitry A. Soshnikov wrote:
let street = user.address?.street
which desugars e.g. into:
street = (typeof user.address != "undefined"&& user.address != null)
? user.address.street
: undefined;
(Just user.address != null would be enough, although perhaps there's a reason
to typeof-test for undefined first that I am missing.)
Yes, != would be enough for property accessor. But the proposal assumes
to test for existence of the global vars as well (where normally we
would got ReferenceError):
let foo = bar?.baz
(regardless that ES6 will have compile-time bindings, it still possible
to create global var at runtime via `this.bar`, though, if there will be
no global object, I'm not sure how this applies to the ES6)
The same with functions (which is even more convenient that just with
properties):
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
undefined;
(I specially avoid optimization with saving intermediate results -- just to
keep clarity)
(Let's hope getBounds has no side effects :-P)
Yeah, right ;)
The ?. form from CoffeeScript is attractive at first glance. For notifying an
ad-hoc observer where the reference to the observer may be null or undefined,
it saves an 'if'. But for deeper optional control flow you need an 'if' anyway,
in my experience.
Yes, of course for some complex `if`s it's better to use `if`s. However,
this:
if (foo.bar) {
if (foo.bar.baz) {
if (typeof foo.bar.baz.quax == "function") {
foo.bar.baz.quax("value")
}
}
}
is "too noisy" in contrast with:
foo.bar?.baz?quax("value");
and first of all, this syntactic sugar is proposed exactly this such cases.
How much is this used in CoffeeScript compared to regular .? Some crude
measurement would be helpful.
Can't say precisely (and even roughly). But personally I used it pair of
times, it was convenient.
Notice also, this form can be used even in this view:
let foo = bar? && baz? : true : false;
which tests for exactly existence of bar and baz.
And default values are also the case sure:
foo ?= default // or foo ?? default (no matter much)
Dmitry.
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss