Hoisting: A Problem with Scattered vars
JavaScript enables you to have multiple var statements anywhere in a function, and
they all act as if the variables were declared at the top of the function. This behavior is
known as hoisting. This can lead to logical errors when you use a variable and then you
declare it further in the function. For JavaScript, as long as a variable is in the same
scope (same function), it’s considered declared, even when it’s used before the var
declaration. Take a look at this example:
myname = "global"; // global variable
function func() {
alert(myname); // "undefined"
var myname = "local";
alert(myname); // "local"
}
func();
In this example, you might expect that the first alert() will prompt “global” and the
second will prompt “local.” It’s a reasonable expectation because, at the time of the
first alert, myname was not declared and therefore the function should probably “see”
the global myname. But that’s not how it works. The first alert will say “undefined”
because myname is considered declared as a local variable to the function. (Although the
declaration comes after.) All the variable declarations get hoisted to the top of the
function. Therefore to avoid this type of confusion, it’s best to declare upfront all variables
you intend to use.
The preceding code snippet will behave as if it were implemented like so:
myname = "global"; // global variable
function func() {
var myname; // same as -> var myname = undefined;
alert(myname); // "undefined"
myname = "local";
alert(myname); // "local"
}
func();