DEV Community

Cover image for Hoisting and Temporal Dead Zone (TDZ)
suraj more
suraj more

Posted on

Hoisting and Temporal Dead Zone (TDZ)

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");
}
Enter fullscreen mode Exit fullscreen mode

Result:
Image description

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";
}
Enter fullscreen mode Exit fullscreen mode

Result:

"Uncaught ReferenceError: Cannot access 'data' before initialization"

Enter fullscreen mode Exit fullscreen mode

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.
see output for TDZ let

Now, change sequence of code:

{
    let data = "hello";
        console.log(data);
}
Enter fullscreen mode Exit fullscreen mode

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.

var and let

Top comments (0)