JavaScript Variable fallback

前端 未结 4 1885
不知归路
不知归路 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.

    0 讨论(0)
  • 2021-02-13 16:04

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

    0 讨论(0)
  • 2021-02-13 16:04

    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.

    0 讨论(0)
  • 2021-02-13 16:24

    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.

    0 讨论(0)
提交回复
热议问题