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

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

    The || operator evaluates the first of its operands that is "truthy".

    [] is an empty array. ([ "Hi!" ] is an array of one string)

    Therefore, the expression x || [] evaluates to x if it's "truthy" or an empty array if it isn't.

    This allows the var1 parameter to be optional.

提交回复
热议问题