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

JavascriptJshint

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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/

Solution 3 - Javascript

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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2413333View Question on Stackoverflow
Solution 1 - JavascriptAlnitakView Answer on Stackoverflow
Solution 2 - JavascriptErik ChristiansonView Answer on Stackoverflow
Solution 3 - JavascriptPointyView Answer on Stackoverflow