function test(){
if(true){
var a = 5;
}
alert(a);
}
test();
I keep getting \'out of scope\' errors in my JS code when I check
The code that you wrote is working. It is just not very readable/maintainable. Declaring the variable a
inside the scope of the if
may give the false impression that a
is only visible inside this scope (which, as this program shows, is not true - a
will be visible throughout the whole function).
This JsLint warning encourages you to place the declaration at the exact scope where the variable is actually used, as follows:
function test(){
var a;
if(true){
a = 5;
}
alert(a);
}