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?
+=
,*=
,-=
,/=
, why wouldn't%=
work?).angle %= 360
orvertexIndex %= numberOfVertices
(for the vertex list of a closed polygon).%=
just last week, without even thinking about it. And I see two uses in the tzcode distribution from twinsun.com/tz/tz-link.htm:tmp->tm_wday %= DAYSPERWEEK;
andrem %= SECSPERHOUR
. In both cases, as Sebastian Negraszus suggested, a quantity (which might have overflowed) is being reduced to its proper range (0-6 or 0-59 in these cases).