||= is much needed?

Brendan Eich brendan at mozilla.org
Tue Jun 12 10:36:51 PDT 2012


Rick Waldron wrote:
> On Tue, Jun 12, 2012 at 11:45 AM, Ryan Florence <rpflorence at gmail.com 
> <mailto:rpflorence at gmail.com>> wrote:
>
>     I use ||= very regularly in ruby and coffeescript, both of which
>     have default arguments.
>

I don't see Ryan's mail.

First, as we've discussed in the past, ||= in Ruby is not what we've 
proposed. In JS, assignment operators expand like so

   A op= B;  ~~>  A = A op B;

with of course a temporary to hold the base of A (which must evaluate to 
a Reference) so side effects are not duplicated.

In Ruby IIRC, A ||= B is A = B unless A (hope I have this right).

This matters if A is an accessor. Do we always set A, even to its 
current value if truthy?

>
>>         I definitely agree that default arguments are a decent
>>         alternative. I can't recall examples where it wouldn't be
>>         enough. Do you have use cases where you would use ||= and
>>         default argument values couldn't be used?
>
>     Its super handy for caching and late/dynamic initialization of
>     object properties.
>
>
>         var events = {
>
>           _callbacks: {},
>
>           on: function (topic, callback) {
>             (this._callbacks[topic] ||= []).push(callback);
>             ...
>           },
>           ...
>         };
>

This is handy, and also idiomatic but to multiple languages.

It's worth considering, but we need to wrestle the semantics to the 
ground. If the left-hand side's value is truthy, I argue there should be 
no useless assignment of that value to the left-hand side.

IOW I favor Ruby semantics. This breaks from JS's C-inspired assignment 
operators, but perhaps we can live with it.

/be


More information about the es-discuss mailing list