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
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; }
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With