Hoisting is a key aspect to understand in JavaScript.
Let's break down hoisting:
When you use var
to declare a variable in JavaScript, the variable is hoisted to the top of its scope. In JavaScript, there are only two scopes: Global and Function. This means that within a function,
function hoistAway() {
console.log(a);
var a = 5;
}
is essentially interpreted as
function hoistAway() {
var a;
console.log(a);
a = 5;
}
In this scenario, the variable declaration is hoisted, but the initialization is not. Therefore, the code would output undefined
instead of 5. However, it acknowledges the existence of a
.
If you omit var
, the declaration isn't explicit so it's not hoisted. For example:
function hoistAway() {
console.log(a);
a = 5;
}
would trigger an error.
In your examples:
window.Foo = Foo;
Foo
was never declared, hence the error message.
window.Foo = Foo;
Foo = function() {
...
};
Once again, since Foo
wasn't explicitly declared, there is no hoisting. It's worth noting that:
window.Foo = Foo;
var Foo = function() {
...
};
won't result in an error. Only the declaration gets hoisted, so if you did something like
var bob = {};
bob.Foo = Foo;
var Foo = function() {
...
};
then bob.Foo
would be undefined
. The case of window.Foo = Foo
is peculiar because Foo
and window.Foo
are equivalent in the Global scope.
Lastly:
window.Foo = Foo;
function Foo(){
...
};
works fine, as function declarations (not expressions) are also hoisted; both the name and definition are lifted up in the code, making it operate as expected.