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

前端 未结 3 1906
猫巷女王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 06:00

    You shouldn't put var declarations in such places. Put the var declaration before the if, and then just set "someVar" to a value.

    Indeed, here you don't need an if statement at all:

    var someVar = !!(something);
    

    will do the same thing. (The double application of ! ensures that "someVar" is set to either true or false, based on the "truthiness" of something.)

提交回复
热议问题