November 17, 2015
What is hoisting?
When looking at a file of code it may seem like the computer will read the code line by line, top to bottom. While this is sometimes true (for simplier applications) there are instances where the computer will read certain things first.
Here we are trying to print a variable a that has not yet been defined.
Setting the variable a to 2 will now print 2 to the console as expected.
However if you move the var a = 2 declaration below the console.log you would get:
Undefined? Why is this happening? Why isn’t the console.log spitting out a ReferenceError since a is not defined before the variable is printed?
When the computer goes to execute this file it hoists all variable declarations to the top of the file but does not assign them a value. So the code we have above is actually read by the computer as:
It is not only variables that get hoisted to the top when the computer executes the code, but function declarations as well.
The function declaration foo is getting hoisted to the top when the computer runs the code. So what the code above looks like to the computer is:
Keep in mind however that function expressions are not hoisted as function declarations are.
So foo here would not be hoisted:
Again the computer is actually interpreting the code as:
One thing to keep in mind is that variables and functions are hoisted to the scope they belong in. In addition, assignments and executables are left in place.