Existential operator (was: ||= is much needed?)

Allen Wirfs-Brock allen at wirfs-brock.com
Wed Jun 20 09:47:56 PDT 2012

On Jun 20, 2012, at 7:18 AM, John Tamplin wrote:

> On Tue, Jun 19, 2012 at 1:34 PM, Jeremy Ashkenas <jashkenas at gmail.com> wrote:
> Allen asks about when you would want to write `foo?.bar()`
> ... the only use case I can think of is when `foo` may or may not be defined, and you know that if it *is* defined, it's going to have a `bar` method on it, and if it *is* defined, you want to call `bar` for its side effects. A bit far fetched.
> It doesn't seem that far-fetched to me -- I seem to constantly write things like this in Java:
> String name = (person != null) ? person.getName() : null;
> IIUC, that could just be written as String name = person?.getName() if this operator were avaialble.
> Maybe you are saying that you don't want to have rigid class structures in JS, but it seems reasonable that if you know person is of type Person it is supposed to have a getName method on it.

yes, but in a static Java-like language such as for you example above, the existence of person implies the existence of the getName method.  The JS equivalent would likely be something like:

   name = (person && person.getName) ? person.getName() : undefined;

using ?. as defined by Brendan this could be:

   name = (person?.getName) ? person.getName( ) : undefined;

I've been arguing that ?. and () could be defined such that the above statement could instead be reduced to:

     name = person?.getName();

However, by Brendan's semantics this reduced form would be equivalent to:

     name = (person && person.getName) ? person.getName() : throw new TypeError;
I was hypothesizing that Brendan's semantics would seldom be the programer's intent for person?.getName() . If an exception was acceptable, why wouldn't you just say:

     name = person.getName();


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120620/b3729d81/attachment-0001.html>

More information about the es-discuss mailing list