Variable Hoisting
Understand variable hoisting in JavaScript. Learn what the engine does behind the scenes to our variable and function declarations and how this results in unexpected behavior. Learn the difference between variable hoisting and function hoisting.
We'll cover the following...
Variable Hoisting
What do you think the following code will log to the console? Take a guess and then run the code to check.
console.log(x); // -> ?var x = 5;console.log(x); // -> ?console.log(y); // -> ?
The second console statement prints 5
as expected, but the first prints undefined
. But the last statement prints an error. What gives? Why do we see an error for y
but not for x
?
The JavaScript Engine
This is because the JavaScript engine alters the structure of our code before it runs it.
Variable declarations are hoisted, or moved, to the top of their available scope. We’re currently in the global scope, so they’ll be hoisted to the top. The code that ...