Function statements are subject to hoisting. This means that regardless of where a function is declared, it is moved to the top of the scope in which it is defined.
(function () {
foo();
function foo() {
alert('foo is beign called');
}
}());
At compile time the structure of that code would change to:
(function () {
function foo() {
alert('foo is beign called');
}
foo();
}());
Function statements are not the only that are subject of hoisting, the var
statement also, because of that (and because JavaScript haves only function-scope) is recommended to have only one var statement at the top of a function, for example:
var bar = "baz"; // on the outer scope
(function () {
alert(bar); // bar is undefined
var bar = "other value";
}());
The alert shows undefined
, because internally the code changed to this:
var bar = "baz";
(function () {
var bar;
alert(bar); // bar is undefined
bar = "other value";
}());