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

后端 未结 8 2028
清歌不尽
清歌不尽 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:07

    The logical operators in JavaScript actually evaluate to one of the two objects. When you use a || b it evaluates to b if a is false, or to a if a is true. Thus a || [] will be a if a is any value that is true, or [] if a is any value that is false.

    It's much more obvious to use if (!a) { a = [] };

提交回复
热议问题