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

后端 未结 8 2006
清歌不尽
清歌不尽 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-15 12:23

    The statement assigns an empty array to var1.


    longer answer and explanation:

    This happens because var1 is not initialized at that time. Non-initialized is a falsy value.

    take this statement:

    var1 = var1 || [];
    

    If var1 is not initialized it becomes an empty array, it if is an empty array nothing happens as its assigned to an empty array, if var1 is false, null, or any other value that javascript things of as false, it becomes an empty array, if var1 is anything other value, nothing happens as it is assigned to itself. (thanks pst for the link).

    In short, its a stupid statement that's neither readable nor useful, but you're smart for wanting to know what it means. :)

提交回复
热议问题