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

user2413333 picture user2413333 · Oct 16, 2013 · Viewed 13.9k times · Source

I have this code:

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

JsHint is saying that "someVar was already defined" on the else statement part. Why is this and how do I fix it?

Thanks

Answer

Alnitak picture Alnitak · Oct 16, 2013

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;
}