I've written the following snippet of code:
var f = function() { document.write("a"); };
function foo() {
f();
var f = function() { document.write("b"); };
}
foo();
I expected the function that prints a
to be called, but it instead gives a runtime error about calling an undefined
value. Why does this happen?
It's about variables hoisting http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html , http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
You code is eqvivalent to the next one;
var f = function() { document.write("a"); };
function foo() {
//all var statements are analyzed when we enter the function
var f;
//at this step of execution f is undefined;
f();
f = function() { document.write("b"); };
}
foo();
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