Artig
2 min readJan 7, 2022

--

What is hoisting in JavaScript?

For understanding the concept of hoisting in detail let us first understand the Global execution context.

Whenever JavaScript executes a piece of code, a Global execution context is created. The GEC(Global Execution Context) is divided into two parts: declaration and execution phase.

So whenever a variable is declared, JavaScript moves the variable to the top of its scope in the declaration phase. This process is known as hoisting.

There are two types of hoisting in JavaScript: variable hoisting and functional hoisting.

Variable Hoisting: The variable hosting in javaScript goes through two phases,i.e. declaration phase and execution phase. There are three ways to create a variable in JavaScript, using var, let, and const. The declaration and execution phase works differently in var and let and const.

In the declaration phase, if we are creating any variable using var, the memory gets allocated for the variable. The variable gets initialized with a unique value called undefined .

console.log(name); // undefined
var name;

Here we got undefined the value of the name because it has been initialized with undefined.

var name="Elizabeth"
console.log(name); // Elizabeth

Here we are getting the name Elizabeth because after declaration phase the, there comes the execution phase, so under the hood what happens is that:

 var name= undefined //delcration phase
name="Elizabeth" //execution phase
console.log(name); // Elizabeth

But with let and const JavaScript works differently:

let name="Arya"
console.log(name) // Arya

Here we are getting the name Arya because under the hood what happens is that:

let name;
name="Arya"
console.log(name) // Arya

But if we try to do this, we will get an error:

console.log(name)  //Uncaught ReferenceError: name is not defined
let name="Arya"

Because if we are declaring the variable with let, it is not initialized with anything, that is why we get this error.

--

--