8

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?

Overv
  • 8,433
  • 2
  • 40
  • 70
  • This phenomenon is certainly detailed in every beginner JavaScript book, not to mention countless beginner tutorials and StackOverflow questions. Hard to understand why people still get stuck on this. –  May 11 '13 at 17:35

2 Answers2

14

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();
aasiutin
  • 210
  • 2
  • 6
0

Since (just like in java) you don't have to worry about the order you define things in in a file a certain situation occurs. When you redefine the variable f it blanks out the other version of f but it is not defined until after so when f is called you get an error.

aaronman
  • 18,343
  • 7
  • 63
  • 78