Operators ||= and &&=

Peter Michaux petermichaux at gmail.com
Wed May 6 11:07:06 PDT 2009

On Tue, May 5, 2009 at 2:59 PM, Brendan Eich <brendan at mozilla.com> wrote:
> On May 5, 2009, at 11:37 AM, Peter Michaux wrote:
>> On Mon, May 4, 2009 at 10:26 PM, Brendan Eich <brendan at mozilla.com> wrote:

>> People often write the following at the
>> beginning of functions for optional parameters
>>  optionalParam = optionalParam || defaultVal;
>> I believe what they are really trying to write is
>>  optionalParam = optionalParam === undefined ? defaultValue :
>> optionalParam;
>> which is what ??= would do.
> You could be right, but the fact is people use ||, which equates falsy
> values to not short-circuit the defaultVal evaluation. This is what the code
> does, not necessarily what was meant. It might be better to pave this
> cowpath and not try to sell the ?? super-highway ;-).

A lot of people don't understand JavaScript falsey value equality and
since || works in their server-side language they assume it works the
same way in JavaScript. It compiles and runs after all! ;-)

A small marketing campaign to encourage the ?: version above might
change what people use.

>> I think optional parameters are the nuisance use case that is fueling
>> any discussion about a ||= or ??= operator.
> Nuisance to you, useful to others

I think I was unclear. Optional parameters are definitely useful. It
is the following idiom's verbosity that is the nuisance (to be
possibly alleviated by a new operator.)

  optionalParam = optionalParam || defaultValue;

>> (though I think they are probably worth adding.)
> Both?

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.

>> 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


More information about the es-discuss mailing list