What is this in [removed] “var var1 = var1 || []”

后端 未结 8 2060
清歌不尽
清歌不尽 2021-02-15 11:43

I just want to increase my core javascript knowledge.

Sometimes I see this statement but I don\'t know what it does:

var var1 = var1 || [];
8条回答
  •  自闭症患者
    2021-02-15 12:24

    Basically, it looks to see if a variable var1 already exists and is "truthy". If it is, it assigns the local var1 variable its value; if not, it gets assigned an empty array.

    This works because the JavaScript || operator returns the value of the first truthy operand, or the last one, if none are truthy. var1 || var2 returns var1 if it's truthy, or var2 otherwise.

    Here are some examples:

    var somevar;
    somevar = 5 || 2; // 5
    somevar = 0 || 2; // 2
    somevar = 0 || null; // null
    

    Values that aren't "truthy": false, 0, undefined, null, "" (empty string), and NaN. Empty arrays and objects are considered truthy in JavaScript, unlike in some other languages.

提交回复
热议问题