JavaScript Hoisting
Hoisting is the behavior of JavaScript that moves the variable and function declarations to the top of the scope, which means variables and functions are declared and allocated memory even before the code is executed.
Let’s dig deep into variable and function declaration in JavaScript now.
function func1()
{
console.log("This is func1");
}
func1();
This is how you would normally declare a function, yes?
So as expected, you will get the log without any issues.
But what will happen if we try to invoke the function before declaring it? It should throw an error right?
func1();function func1()
{
console.log("This is func1");
}
But NO. The output will be the same. But how did this happen? The answer to that question is Hoisting.
JavaScript allocates memory to all the variables and functions before the code is actually executed. So when the code is actually running, it already has its functions and variables in the memory. This is called hoisting in JavaScript.
Now let’s try something else.
console.log(var1);var var1 = 10;
What do you think will happen here? Just like the above example, JavaScript has hoisted the variable and we should be getting 10, yes?
But again NO. See the output of the above code.
undefined
What do you think happened here?
Variables and functions have different behaviors when it comes to hoisting. Although JavaScript allocates memory for variables, it doesn't initialize them with the assigned values during hoisting. Instead, variables are assigned undefined as their initial value. When the code is executed, they will get their actual values assigned to them. This is the reason we got undefined and not a ReferenceError.
Now let’s try to declare a variable with the let keyword and see what happens.
console.log(var1);let var1 = 10;
You would guess that since variables are hoisted and assigned undefined, the result should be undefined, yeah?
Here, when we run the code, we will get a ReferenceError as below.
ReferenceError: Cannot access 'var1' before initialization
So what does this mean? Was this variable not hoisted?
Variables declared using let and const keywords are also hoisted but they are not initialized. The memory for this variable is not allocated in the Global object but in a different memory space, in which variables cannot be accessed until they are initialized. (You can see this clearly if you debug in the browser and check the Scope when the code is in the first line)
This is said to be a temporal dead zone. The time from the moment the variable was hoisted until it is assigned its value is known as the temporal dead zone.
Thanks For Reading!