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

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

    Javascript or (||) works a bit differently to some other languages, it returns the first "truthy" value instead of a boolean. This is being used in this case to say "Set the value of var1 to var1, but if that value is "falsey" set it to []".

    This is often used to set a "default" value to a variable that may or may not be set already, such as an argument to a function.

提交回复
热议问题