Operators ||= and &&=

Ash Berlin ash_es4 at firemirror.com
Wed May 6 13:43:34 PDT 2009

> I don't think ||= and ??= are very difficult to define clearly.
> Perhaps just a line each in terms of the expanded syntax. I don't
> think they would add much bloat to engines. Perhaps just better to add
> them both and move on to discussing classes, lambdas, or processes.

a ||= b;
a = a || b;

a ??= b;
a = a === undefined ? b : a;

>>> And in this syntax will default values be used if the parameter is
>>> falsey or only if it is undefined?
>> Only if the actual parameter is absent.
> Well that is more useful than the ||= or ??= idioms at the top of the
> function body anyway. Someone passing the value "undefined" to a
> function causes problems for the idioms.
> Someone may want to still use the ||= or ??= idioms for testing
> properties inside an object passed to the function. I do that when the
> last parameter to a function is a bunch of different named optional
> parameters. Unfortunately simple idiom tests for properties inside an
> object could still be fooled if someone sets a property to
> "undefined".

If someone calls myFunc({option: undefined}) I assume the meant to  
explicitly pass an undefined value. The correct idiom for testing this  
would be

var opt = "option" in arg ? arg.option : "default";

But this is a fairly rare usage.

Perl has has ||= for a long time (or-equals: var a = a || a_default)  
and Perl 5 v10 added the defined-or-equal '//=' and defined-or '//'  
operators. I'm not a huge fan of the sigil chosen for perl mind:

   $foo //= "default";
   $foo = defined $foo ? $foo : "default";

You could make a case for adding a ?? operator for symmetry. Example  
of usage:

some_func(a, b ?? "c" );

P.S. Appolgies to anyone who got a copy of this directly. I sent it to  
the list from the wrong address previously. 

More information about the es-discuss mailing list