JavaScript Variable fallback

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

提交回复
热议问题