Posts Tagged ‘hoisting’

In this post we will discuss about the scope of a javascript variable and how “hoisting” works in javascript. Let’s start with a simple global variable definition.


In this code “a” is defined as a global variable and should be accessible to all the functions.So quite naturally the function “f” will print “global” i.e. value of the global variable “a” in the console.

In the code below, we have introduced a small change and added declaration of another variable named “a” in the function “f”.


Here the program will give precedence to the local variable “a” and will print “local” to the console. So far it’s quite intuitive.


Here we are trying to access the value of “a” first followed by the local variable declaration of same name and then again printing it’s value to the console. Most of us would expect to the following in the console.



It will print the following instead:


This happens because the way javascript handles variable declaration and initialization.It first scans the function and finds out all the variables and declares them on top but does not initialize them. Then when the code executes it provides the initialization value in the actual line where its defined. So when the first console.log statement executes it sees that there is a variable named “a” defined but not initialized so it will print “undefined”.

This is how variable hoisting (moving to the top) works in javascript where the declarations are only hoisted and not the initialization.

So this can lead to undesirable behavior and it is safe to declare the variable at the top of the function before its use.