Check this fiddle or the below code and tell me why is the output of this script is 10
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();
Check this fiddle or the below code and tell me why is the output of this script is 10
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();
Because the var
in the function, hoists the variable up to the top. As if you declared it at the top of the function, and so foo
is treated as a local variable in the current scope, the foo
in the global scope is not affected. Your code is the same as this:
var foo = 1;
function bar() {
var foo;
if (!foo) {
foo = 10;
}
alert(foo);
}
bar();
As you can see, foo
is declared at the top of the function and is undefined
, but importantly doesn't get a value until inside the if statement.