Are let and const hoisted?

Are let and const hoisted?

What is hoisting?

Hoisting is the process that makes some type of variables accessible/usable in the code even before they are declared. Before the execution, the code is scanned for variable declarations in the global scope. For each type of data, the hoisting is performed in a different method.

Hoisting of var dataType

When a variable is initialized in the var dataType then those variables are stored in the global scope and they can be accessible even before the declaration.

image.png

We get output as undefined but it'll not throw any error because before the execution itself the memory has been allocated to the 'value' variable. The value variable is present in the window object and it is placed in the global scope.

All the var dataTypes are assigned to undefined in the global scope before the declaration.

Hoisting in let and const data types

Generally, we consider that let and const are not hoisted because they are not placed in the global scope before the execution. Variables declared in let and const data types are placed in block scope. If we try to initialize those variables before the declaration then it throws a reference error.

letandconst1.png

So from the error, we can see that variable is not even present in the global scope and no storage is allocated for the variable.

Where those variables are stored until the execution of code?

The variables which are declared in the type of let and const, that data will be stored in the temporal dead zone.

Temporal dead zone: It is the area/zone in which the variables are stored as undefined until the code is executed. So when we debug the code using google developer tools, we can verify that the variable will be present in the local scope and the variable is set to undefined.

letandconst2.png

So we can observe in the source window that "a" is set to undefined even before the line containing the variable is executed. The variable is stored in another scope called script scope. let and const dataType are not present in the global scope and window object.

Conclusion.

The Hoisting of both let and const dataTypes are the same. So we can conclude that let and const types are also hoisted for time being in Temporal dead zone whereas var data type is hoisted as they are present in the global scope even before execution.