Hoisting in JavaScript
Hoisting is a term that i thrown around a lot if you are reading up on JavaScript. But what is hoisting? The verb hoist is defined as “an act of raising or lifting something”. So we must be raising something up. But What? Variables and function declarations are what are hoisted to the top of the code. By verb definition, the variables and function declarations are what are moved to the top of scope. That is how it’s actually been explained to me in many tutorials, videos, and even in various lectures. However, this isn’t actually he case! “The variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.” [A] So the code isn’t moved, but by declarations being placed in memory, you can call those declarations in your code before they are read later. Meaning, referenced decelerations can be placed under callers in code.
If we look at the code below, we see that the function caller is accessing function toBeHoisted before it’s defined. Thanks to JavaScript’s hoisting, this is not a problem.
function caller(){ let x = toBeHoisted(); console.log(x+5); } function toBeHoisted(){ return 5; } caller() //10
.What we have to take heed of however is that initializations are NOT hoisted, only definitions. So this is why it is said only functions are hoisted, even though technically, only declarations are hoisted, which can be variables or functions. In practice, even if the variable is initialized upon declaration, it doesn’t satisfy any callers In the example below, if we define variable toBeHoisted , but initialize it after function caller, then we will have an error
function caller(){ let x = toBeHoisted; console.log(x+5); } caller() //toBeHoisted is not defined, we get NaN var toBeHoisted = 95;
To see that hoisting does affect variables, we could initialize the variable BEFORE declaring it, and then the declaration is hoisted.
toBeHoisted = 95; function caller(){ let x = toBeHoisted; console.log(x+5); } caller() //100 var toBeHoisted;
.
As an aside, if we change from a var decleration to let decleration, that will not be hoisted and we get an error
toBeHoisted = 95; function caller(){ let x = toBeHoisted; console.log(x+5); } caller() //ReferenceError: toBeHoisted is not defined let toBeHoisted;
.