Hoisting and TDZ?

·

2 min read

hoisting.png

In JavaScript, Hoisting is a special case which allow you to use variable and function before initialization . this hoisting feature is only present javascript.

console.log( fruits );
var fruits = " Mango "

In the upper case console.log() give undefined without giving an error. Hoisting makes the computer process declarations before any other code.

This is because the JavaScript interpreter splits the declaration and assignment of functions and variables: it "hoists" your declarations to the top of their containing scope before execution.

Variable hoisting in Javascript If we declare a variable with let, const and var

For Example:

console.log( value1 ) ;
console.log( value2 ) ;
console.log( value3 ) ;

var value1 = " Ram " ;
let value2 = " Shyam " ;
const value3 = " Shubham " ;

The first console.log(value1) outputs undefined because value1 is hoisted and given a default value (not because the variable is never declared). Using an undeclared variable will throw a ReferenceError instead:

Temporal Dead Zone

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.

Unlike var, which can be accessed before it is declared, variables declared with let and constants declared using const cannot be accessed before their declaration.

console.log( value1 );  // undefined
var value1 = " Ram "

console.log( value2 ) // ReferenceError
var value2 = " Shyam "

So, if the let and const are also hoisted, why is it that they cannot be accessed before their declaration? The answer to this lies within the concept of the Temporal Dead Zone (TDZ).

Variables declared using let and the constants declared using const are hoisted but are in a TDZ. This prevents them from being accessed before their declaration has actually been executed during the step-by-step execution of the code.

Temporal Dead Zone is the period of time during which the let and const declarations cannot be accessed.

Temporal Dead Zone starts when the code execution enters the block which contains the let or const declaration and continues until the declaration has executed.