What is Hoisting???
In JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
Let's try to learn this terminology with example
debugger;
console.log(a);
abc();
var a = "Hello";
function abc () {
console.log("Print Hello");
}
as per above image "dubugger;" is set on first line to see how thinks works.we are still on first line, but variable and function have gotten memmory allocation.
because, before executing first line interpretor goes through code and do memmory allocation for all functions and variables.
This is one of stage of creating execution context. Generally, There are two stages:
- Assigns memory to every variable, class or functions
- Starts executing code line by line.
This first stage is called hoisting. Now using this concept we will understand another important topic which is Temporal Dead Zone. so,
What is Temporal Dead Zone???
as per MDN defination,
A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value.
as per defination we get variable type should be block scoped like "let" or "const" ( not var because it is functioned scope,we will see at the end.)
so let's understand by example:
{
console.log(data);
let data = "hello";
}
Result:
"Uncaught ReferenceError: Cannot access 'data' before initialization"
it gives reference error for data, because as we seen in hoisting, it trys to create execution scope and assigns memory for every variable, class or function.but, let is not global scoped, so it is not accessible.
Now, change sequence of code:
{
let data = "hello";
console.log(data);
}
so, error is gone and it prints "hello".
for const, it works same way but const varible needs to initialize with some value as per its rule.
Now let's see for var, var is special keyword compare to earlier two. because it is global scoped, we can access it before declaration as it is added to global scope compare to let which is added to block scope.
Top comments (0)