Please can someone explain to me what this line of code does:
var list = calls[ev] || (calls[ev] = {});
My best guess:
It's setting the variable "list" with the value of calls.xxx, where xxx is a variable, ev. If calls[ev] doesn't exist, then it's creating it as an empty object and assigning that empty object to "list". Is that right?
Why are the parenthesis being used? Where can I find out more info on using || when setting variables, and the use of parenthesis in this context? Thanks!
A fallback value is a contingency option to be taken when the preferred value is not available.
symbol is used to indicate whether the expression defined is false or not. For example, !( 5==4) would return true , since 5 is not equal to 4. The equivalent in English would be not .
The double pipe operator ( || ) is the logical OR operator . In most languages it works the following way: If the first value is false , it checks the second value. If that's true , it returns true and if the second value is false , it returns false .
Anyways, the default value of a variable in JavaScript is null or undefined .
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).
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
.
||
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With