what do you mean by Hoisting and Temporal Dead Zone in JS ?

Photo by RetroSupply on Unsplash

what do you mean by Hoisting and Temporal Dead Zone in JS ?

Hoisting is a concept that enables us to extract values of variables and functions even before initializing/assigning value without getting errors and this happens during the 1st phase (memory creation phase) of the Execution Context.

In the context of JavaScript, "hosting" refers to the concept of variable and function declaration movement within the code during the execution phase. JavaScript has a behavior known as hoisting, where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use a variable or call a function before it is declared in the code.

Note: JavaScript only hoists declarations, not initializations.

JavaScript allocates memory for all variables and functions defined in the program before execution.

Let's look at an example to illustrate this--

console.log(x); // Output: undefined
var x = 5;

// The above code is interpreted as follows during execution:
// var x;
// console.log(x); // Output: undefined
// x = 5;

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.

NOTE

  • A block is a pair of braces ({...}) used to group multiple statements.

  • Initialization occurs when you assign an initial value to a variable.

Suppose you attempt to access a variable before its complete initialization. In such a case, JavaScript will throw a ReferenceError.

So, to prevent JavaScript from throwing such an error, you've got to remember to access your variables from outside the temporal dead zone.

Let's look at an example to illustrate this--

console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;

In the example above, the variable x is declared using let, and when the console.log(x) statement is encountered, JavaScript throws a ReferenceError because x is in the Temporal Dead Zone. The declaration of x is hoisted to the top of the block scope, but its initialization (x = 5) is not hoisted. Accessing x before the initialization leads to an error.

This behavior helps catch potential issues with variable usage before they are initialized, providing more predictable and less error-prone code.

It's worth noting that the Temporal Dead Zone doesn't apply to variables declared with var. With var, the variable is hoisted to the top of its scope, and its value is undefined until it is explicitly initialized. In contrast, let and const variables in the Temporal Dead Zone remain inaccessible until their declaration is encountered in the code.