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

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

    While this has been pointed out as 'being a silly statement', I present the following two counters:

    (Just to keep people on their toes and reinforce some of the "finer details" of JavaScript.)

    1)

    var is the variable is already local. E.g.

    function x (y) {
      var y = y || 42 // redeclaration warning in FF, however it's "valid"
      return y
    }
    x(true) // true
    x()     // 42
    

    2)

    var is function-wide annotation (it is "hoisted" to the top) and not a declaration at the point of use.

    function x () {
      y = true
      var y = y || 42
    }
    x()      // true
    

    I do not like code like either of the preceding, but...

    Because of the hoisting, and allowed re-declarations, the code in the post has these semantics:

    var var1
    if (!var1) {
      var1 = []
    }
    

    Edit I am not aware of how "strict mode" in Ed.5 influences the above.

提交回复
热议问题