Please can someone explain to me what this line of code does:
var list = calls[ev] || (calls[ev] = {});
My best guess:
It\'s setting t
||
or 'logical OR' has a higher precedence than the assignment operator =
, thus the parentheses are necessary to ensure this idiom evaluates in the right order
The other thing to be aware of is that many languages, Javascript included, provide short-circuit evaluation of boolean operators like AND and OR. If the first operand of a logical-or evaluates true, there is no need to evaluate the second operand, as it would make no difference to the result.
Understand this, and you'll see this isn't some special assignment syntax, but an idiom, or pattern, that exploits a language feature to provide a more compact representation of an idea.
This code is equivalent to
var list;
if (calls[ev])
list = calls[ev];
else {
calls[ev] = {};
list = calls[ev];
}
Two features of the language are used:
a || b
. If a
is true
then b
is not evaluated). Thus, if you assign var v = a || b;
and a
evaluates to something that can be cast to true
, then b
is not evaluated.var a = b = c;
)The parentheses are necessary to avoid this interpretation:
var list = (calls[ev] || calls[ev]) = {};
(which is an error).
you are right about your first guess. This is a common pattern for initialising javascript namespaces. It serves to make sure you dont overwrite a previous object with the same name. Most popular libraries will do something similar in order to create their namespace objects.
The parenthesis is there so that the expressions are evaluated in the proper order.
Your guess is right. This is a common way to declare "default" values for variables in JavaScript.
function foo(bar) {
var bar = bar || 0; //This sets bar to 0 if it's not already set
console.log(bar);
}
The way this works is that in JavaScript, an undefined variable is falsy, meaning that in any boolean comparaison operation, it will evaluate to false
. You can then use the OR operator to combine two values and it will return the first value that evaluates to true
.