According to ECMA-262, part 11.13, following is the exhaustive list of compound assignment operators: *= /= %= += -= <<= >>= >>>= &= ^= |=
.
According to the part 11.11, var c = a || b
will put a
value into c
if ToBoolean(a)
is true and will put b
value into c
otherwise. As such, the logical OR is often used as the coalesce operator, e.g.
function (options) {
options = options || {};
}
Frequently enough, coalesce is used to specify the default value for the variable, as was shown above: a = a || b
.
It seems that compound assignment operator ||=
would be really useful, allowing to write the code above in a shorter and cleaner fashion: a ||= b
. However, it is not there (although *=
, +=
and other compound assignment operators are).
The question is, why?
Best Answer
One possible reason is that the logical operators
&&
and||
have "short-circuiting" behavior. The right-hand operand of&&
and||
is not evaluated unless necessary. Perhaps for this reason the language designers decided that the meaning of an expression likea ||= f()
was not obvious, and so such operators were better left out.