July 08, 2014

JavaScript Variable Hoisting

One of the little known nuances of JavaScript, is that the interpreter organizes functions and variables per scope by declaring them at the beginning of the scoping container, regardless of their order in the written script. Here's an example:

Displays:

x=undefined
x=1
Uncaught ReferenceError: y is not defined
In the above example, we're logging the value of variables x and y before they are declared, however, x has a value of
undefined
whereas y throws an error. So what's the difference? Neither variable has been declared when we are accessing them. Why do we only get an error when referencing y?

The reason is that the JavaScript interpreter reorganizes the declaration of ALL varibles within a scope to the top of the scope - in our case our scope is the function
showVariableValues()
. So in reality, our above code will be reorganized as shown below:

Notice that the declaration of var x has been "hoisted" to the top of the scope, but only the declaration. The initialization of the variable remains in its original spot. Once this variable was declared, JavaScript set its value to
undefined
- the JavaScript default. So that's why when we write the value of x, it's value is
undefined
, whereas y just throws an error because it has not been declared.

So the lesson is: always declare your variables at the beginning of their scope - if you don't, JavaScript will reorganize your code for you. If you think about it, you could probably come up with scenarios with much more confusing results than this simple example.

Share |