Loading...
JavaScript

What is Hoisting and Temporal Dead Zone in ES6

Hoisting is important JavaScript concept introduced in ECMAScript 6 (ES6) where variables and function declarations (declared using var) are moved to the top of their scope before code execution. Inevitably, this means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

Variable Hoisting:

It is important to note that, JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be undefined.

// Hoisted
console.log(num); // undefined
var num; // Declaration

// Not hoisted
console.log(num); // ReferenceError: num is not defined
var num = 10; // Initialization

Function Hoisting:

let’s consider an example to understand function hoisting.

// Calling function before declaration
add(5, 10); Output: 15

function add(x, y){
   console.log(x + y);
}

As you see, the function add() is called before it was declared, but the code will work fine without any error because of hoisting mechanism. JavaScript will consider the above code as:

function add(x, y){
   console.log(x + y);
}
add(5, 10); Output: 15

The add() function declaration is moved to the top before executing it.

“Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. “

Temporal Dead Zone:

In ECMAScript 6 (ES6), accessing a let or const variable before its declaration within its scope causes a ReferenceError (i.e. does not support hoisting). The time span when that happens, between the creation of a variable’s binding and its declaration, is known as the Temporal Dead Zone.

console.log(num); // ReferenceError: num is not defined
let num;

To learn more about let, const and other new features introduced in ES6 you may read this article.

Share this article with your friends
Leave a Reply

Your email address will not be published. Required fields are marked *