Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is going on with JavaScript scope here? [duplicate]

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?

like image 863
Overv Avatar asked May 11 '13 17:05

Overv


1 Answers

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();
like image 70
aasiutin Avatar answered Nov 16 '22 04:11

aasiutin