According to ECMA-262, part 11.13, following is the exhaustive list of compound
ID: 646679 • Letter: A
Question
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?
Explanation / 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 like a ||= f() was not obvious, and so such operators were better left out.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.