JavaScript Variable fallback

前端 未结 4 1889
不知归路
不知归路 2021-02-13 15:28

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

4条回答
  •  不知归路
    2021-02-13 15:59

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

提交回复
热议问题