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

后端 未结 8 2032
清歌不尽
清歌不尽 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.

    0 讨论(0)
  • 2021-02-15 12:25

    It assigns an empty array to var1, if the boolean representation of it is false (for example it hasn't been initialized).

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