Hoisting and Temporal Dead Zone in JavaScript

Apurv Thakur
2 min readDec 3, 2020

JavaScipt is considered as one of the most difficult languages by various developers around the globe but at the same time it is the most loved language also. Why is it so? It is because at times developers tend to skip the basic concepts of JavaScript and directly jump into its various frameworks.

One such basic concept of JavaScript is Hoisting. So what is hoisting in JavaScript?

The variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

The above statement is the definition of hoisting according to MDN docs. Still confused? Let’s dive deeper into hoisting!

Hoisting basically means that all the variable declaration or function declaration in JavaScript is moved to memory during the compiling phase itself. It means that your function and variables are recognized by JavaScript as soon as your code compiles. So variable declared at any point in your code gets its memory as soon as the code compiles, which makes it possible in javascript to use variables or functions to use them before their declaration and initialization. This, however, is not recommended because it may lead to various bugs when you are writing a big chunk of code.

Let's have a look at the code snippet below:

When you look at the above code, the function is called before its definition and it works fine. Similarly, the variable v is used before it’s declared and initialized and it does not show an error. This is HOISTING in JAVASCRIPT.

But in the above code, if we try to replace var with let or const. We get an error as below:

Uncaught ReferenceError: Cannot access ‘v’ before initialization
at index.js:10

What does this mean? Is only Var hoisted in JavaScript? Are let and const not hoisted in JavaScipt?

So, let and const are also hoisted in JavaScipt. BUT, they are not stored in a global object instead they are stored in a temporal dead zone. TDZ is the area in the scope of the definition between the declaration of the let const variable and its usage before its declaration. For example, in the above code snippet if we replace var in line 10th with let or const, then the TDZ would be from line 1 to line 10.

So next time someone asks you if let and const are hoisted, your answer should be a YES along with the description of the temporal dead zone.

Enjoyed reading? Share this with your connections if you think this might help them understanding Hoisting better.

--

--

Apurv Thakur

I am Apurv, final year graduation student at NIT Srinagar. I am a full stack developer and a competitive programmer. Exploring JavaScript to the depth currently