JavaScript Variable fallback

喜夏-厌秋 提交于 2019-12-21 03:53:00

问题


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!


回答1:


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:

  1. The shortcut computation of boolean expressions (consider 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.
  2. The assignment statement evaluates to the last assigned value (to enable var a = b = c;)

The parentheses are necessary to avoid this interpretation:

var list = (calls[ev] || calls[ev]) = {};

(which is an error).




回答2:


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.




回答3:


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.




回答4:


|| 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.



来源:https://stackoverflow.com/questions/9586278/javascript-variable-fallback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!