I found a bug in my site, because of this strange behavior.
The second function alerts “undefined” instead of “one”.
function test() {
var myParam = "one"
if (false) {
var myParam = "two";
}
alert(myParam);
}
test(); // alert "one"
function testAjax() {
var myParam = "one";
$.ajax({
url: "http://url-to-get-error",
error: function(){
if (false) {
var myParam = "two";
}
alert(myParam);
}
});
}
testAjax(); // alert "undefined"
And if I comment block bellow, alerts “one” correctly.
Someone knows why?
if (false) {
var myParam = "two";
}
See in http://jsfiddle.net/EaW8D/2/.
UPDATE
Guys, I know how to to solve the problem, thanks a lot!
But the question is WHY js is setting undefined in a block
that NEVER run (if (false)).
You are re-declaring
myParaminside the error handler, shadowing the variable with the same name in the outer scope. Variable declarations are “hoisted” to the top of the function, so your code is effectively the same as:and since the
ifblock is never executed,myParamwill beundefined(the default value for uninitialized variables).Here is a simple example to proof this behaviour. If the variable was not hoisted,
foowould become a global variable (assuming non-strict mode) and a property ofwindow, but it does not:To solve this problem, simply remove
var, so thatmyParamrefers to the variable declared in the outer scope,testAjax: