Referencing a JavaScript value before it is declared – can someone explain this

Function declarations are subject of hoisting, and they are evaluated at parse time, by hoisting means that they are available to the entire scope in where they were declared, for example:

foo(); // alerts foo
foo = function () { alert('bar')};
function foo () { alert('foo');}
foo(); // alerts bar

The first call to foo will execute the function declaration, because at parse time it was made available, the second call of foo will execute the function expression, declared at run-time.

For a more detailed discussion about the differences between function expressions and function declarations, check this question and this article.

Leave a Comment