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

前端 未结 3 1820
猫巷女王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:52

    JS variables do not have block scope, they have "function" scope (or sometimes global).

    The declaration (but not the assignment) is "hoisted" to the top of the function.

    jshint is warning you that you have two such declarations - your code is equivalent to:

    var someVar;
    var someVar;  // warning!
    if (something) {
         someVar = true;
    } else {
         someVar = false;
    }
    

提交回复
热议问题