Var Declarations and Hoisting
Variable declarations using var
are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where the actual declaration occurs; this is called hoisting. For a demonstration of what hoisting does, consider the following function definition:
function getValue(condition) {
if (condition) {
var value = "blue";
// other code
return value;
} else {
// value exists here with a value of undefined
return null;
}
// value exists here with a value of undefined
}
If you are unfamiliar with JavaScript, then you might expect the variable value
to only be created if condition
evaluates to true. In fact, the variable value
is created regardless. Behind the scenes, the JavaScript engine changes the getValue
function to look like this:
function getValue(condition) {
var value;
if (condition) {
value = "blue";
// other code
return value;
} else {
return null;
}
}
The declaration of value
is hoisted to the top, while the initialization remains in the same spot. That means the variable value
is actually still accessible from within the else
clause. If accessed from there, the variable would just have a value of undefined
because it hasn’t been initialized.
It often takes new JavaScript developers some time to get used to declaration hoisting, and misunderstanding this unique behavior can end up causing bugs. For this reason, ECMAScript 6 introduces block level scoping options to make the controlling a variable’s lifecycle a little more powerful.