Hoisting in JavaScript

Introduction

The concept of hoisting in JavaScript can sometimes be confusing for beginners, but it is asked often in Tech interviews. So let's try to understand hoisting with few simple examples.

Hoisting

Even before code execution starts, JavaScript initializes functions and variables used in the code. This is called hoisting.

In below code "Hello World" will be displayed even before function fn_a() is defined.

fn_a(); // Hello World

function fn_a() {
  console.log("Hello World");
}

fn_a(); // Hello World

The variables declared using var, are initialized as undefined before any value is assigned.

So line 1 will display undefined while line 5 will display Hello.

console.log(b); // undefined

var b = "Hello";

console.log(b); // Hello

In case of let and const variables line 1 would throw below error:

ReferenceError: Cannot access 'b' before initialization

This is because let and const variables are initialized (as undefined) in the Temporal Dead Zone and can only be accessed after a value is assigned.

To better understand this we must learn about the Creation Phase and the Execution Phase of JavaScript code.

The Creation Phase

The Creation phase, also referred to as the Compilation phase, is when JavaScript scans through the entire code and allocates some memory for the functions and variables used in the code.

Functions will be initialized in this phase, and variables will be initialized as undefined.

Once the Creation phase is complete, the Execution phase begins.

The Execution Phase

In this phase JavaScript reads through the code line-by-line from top-to-bottom and executes it. The undefined variables are assigned values as written in the code, and functions are executed.

The let and const variables if assigned any value can be accessed. Else we cannot access those variables because they're hoisted in the Temporal Dead Zone which is a separate memory space that exists only in the time in between the Creation phase and the Execution phase.

Conclusion

That's all there is to hoisting. Stay tuned for more such articles!