Why the following code will return “obvious”, “surprise!” (and lastly “how come?”). It should return “expected”, isn’t it?
In the first if we used anonymous functions, in the second we used ‘named’ functions.
var a = 5;
if (a == 5) {
var b = function () {
return "obvious";
};
} else {
var b = function () {
return "never";
};
}
if (a == 5) {
function c() {
return "expected";
}
} else {
function c() {
return "surprise!";
}
function d() {
return "how come?";
}
}
alert(b());
alert(c());
alert(d());
So this means, function a(){} is NOT equal to var a = function (){}.
So, the second question, why JS needs this peculiar behavior? What’s the benefit of this ?
All variable declarations and function declarations are hoisted to the top of the scope, in this case the top of the script. This means the code is interpreted as if it was,
Note that the last if statement is empty as all the function declarations they contained were hoisted. The second declaration of the function
cobscures the first.I recommend you avoid using funciton declaration syntax in a block statement. It is techincally not legal JavaScript but every browser supports it even though it leads to confusion as you have noted.
Correct. This has never been the case.
JavaScript hoists function declarations to allow function declared later in the script to be used by function earlier in a script. This allows much more flexiblity in code organization.