Hoist!
Robin Kim
—August 05, 2014
You will learn:
- A variable declaration is hoisted.
- A variable initialization is not hoisted.
- A function declaration is hoisted.
- A function expression is not hoisted.
Need a refresher on these terms before learning about hoisting? Check out my previous post: Write and Execute JavaScript Functions!
Computers Read Code Differently
We, humans, read code left to right, top to bottom, while computers like to skim through and pick out what they like first. This JavaScript behavior is called hoisting and may lead to strange behavior if you're not familiar with the topic.
Variable Hoisting
A variable declaration, or the act of stating the existence of a variable, is hoisted to the top of its relevant scope, no matter where it is in your code. (Even if you write it as the very last line of your function, it will be hoisted to the very top of that same function.)
The following lines of code are valid:
x = 5;var x;
They are essentially interpreted like this:
var x;x = 5;x;
A variable initialization, or the act of assigning the value of a variable, is not hoisted. It stays locked in place.
The following sample works fine:
var x = 5;console.log(x); // 5
Yet the next does not:
console.log(x); // undefinedvar x = 5;
Here's another way to write the equivalent of the last example:
var x; // variable declaration hoisting in action!console.log(x); // undefinedx = 5; // variable initialization locked in place!
Function Hoisting
A function declaration, or a free standing function (not assigned to a variable), is also hoisted to the top of its relevant scope.
This example executes without a hitch:
jump(); // 'how high?'function jump() {console.log('how high?');}
The function is pulled to the top as if the previous lines are written as such:
function jump() {console.log('how high?');}jump(); // 'how high?'
Functions are not hoisted when they are assigned to variables, so don't be fooled! Will the following lines work correctly?
jump();var jump = function() {console.log('how high?');}
They will not! Here's an equivalent of the previous lines:
var jump;jump(); // error! jump() is not a function!jump = function() {console.log('how high?');}jump(); // this new jump(), which I just added, would work just fine
Good Coding Technique
Since the JavaScript interpreter pulls apart the "statement of existence" and "assignment of value," a good coding practice is to declare all of your variables at the top of your program (or function) to prevent any confusion and mistakes!