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:

  1. function getValue(condition) {
  2. if (condition) {
  3. var value = "blue";
  4. // other code
  5. return value;
  6. } else {
  7. // value exists here with a value of undefined
  8. return null;
  9. }
  10. // value exists here with a value of undefined
  11. }

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:

  1. function getValue(condition) {
  2. var value;
  3. if (condition) {
  4. value = "blue";
  5. // other code
  6. return value;
  7. } else {
  8. return null;
  9. }
  10. }

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.