function bar() {
return foo;
foo = 10;
function foo() {}
var foo = 11;
}
console.log(typeof bar());
typeof bar returns function?! why not number?
JS functions are executed in two passes three passes. First, the engine walks through the code, looks for function declarations and hoists them (=moves them to the top), second, it hoists variable declarations (unless the same name is already hoisted), finally it runs the "normalized" code.
In your snippet, the engine picks function foo
and moves it to the top of the function. The subsequent var foo
is ignored.
This results in the following "normalized" code:
function bar() {
function foo() {}
return foo;
foo = 10;
foo = 11;
}
which explains your results.
Reference: Declaration Binding Instantiation, notice steps 5 and 8.
return foo
just references to function foo() {}
so it's returning Function
function bar() {
return foo; // function foo() {}
foo = 10;
function foo() {}
var foo = 11;
}
alert(typeof bar()); // function
another scenario
function bar() {
return foo; // returns foo undefined as no value is assigned
foo = 10;
var foo = function () {} // referenced to variable
var foo = 11;
}
alert(typeof bar()) // undefined
here it will return number
function bar() {
foo = 10;
return foo; // 10
function foo() {}
var foo = 11;
}
alert(typeof bar()); // number 10
this too will return a closure function which returns a number
function bar() {
foo = 10;
return function () {
return foo
}
var foo = 11;
}
alert(typeof bar()()); // number 10
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