Why is Jshint saying “variable already defined” in this if statement?

前端 未结 3 1818
猫巷女王i
猫巷女王i 2021-02-02 05:09

I have this code:

 if ( something is true ) {
        var someVar = true;
    } else {
       var someVar = false;
    }

JsHint is saying that

3条回答
  •  既然无缘
    2021-02-02 05:55

    This is due to hoisting.

    In javascript, no matter where you define a new variable with var, it moves it to the top of the function you are in. Your code is producing the following above your if block at the top of the function:

    var someVar;
    var someVar;
    

    Here is a tutorial to explain hoisting:

    http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/

提交回复
热议问题