What is Hoisting in JavaScript?

Last updated on September 12, 2022

In JavaScript, a mechanism that moves function and variable declarations to the top scope is called Hoisting. It is JavaScript default behavior in which we can use variables before declaring.

In simple words, let’s understand it by an example. In the picture below we have two blocks orange and green. Let’s say JavaScript executes an orange block first that is the top scope and then green block. When JavaScript executes an orange block, the mechanism takes all declarations and puts them in the orange block. It means JavaScript moved declarations to the top scope.

JavaScript Hoisting

Once the orange block execution ends then JavaScript executes the green block. So in the green block JavaScript gets all declarations ready.

Hoisted Variable in JavaScript

Let’s see an example, we have a variable i with var keyword and we assigned 10 to it.

var i = 10;

console.log(i);
// Output: 10

It returns 10, which is very simple. In variable i we stored 10 and console.log(i) simply prints in the browser console.

Now look at the example below, in which we have moved variable i to down. In this case we will be getting different results.

console.log(i);
// Output: undefined

var i = 10;

As you can see we are using the console.log() function that prints undefined in the browser console. However, 10 is assigned to variable i. It is because hoist works with var keyword and when JavaScript runs the code the hoist mechanism declares variable i and initializes it with undefined value. That’s why console.log() function prints undefined instead of 10.

Non Hoisted Variable in JavaScript

In JavaScript, let and const are not hoisted variables. Now let’s check the above code with the let keyword.

let i = 10;

console.log(i);
// Output: 10

We have output 10 in the browser console. Now let’s change the order,

console.log(i);
// Output: Uncaught ReferenceError: Cannot access 'i' before initialization

let i = 10;

This time we got the below error message in the browser console.

Uncaught ReferenceError: Cannot access 'i' before initialization

It says it can’t be accessed before initialization which means the hoist mechanism does not initialize any value to the i variable because of the let keyword. That’s why we say the let keyword is a non hoisted variable.

Conclusion

In this article, we have learned the hoisting mechanism and usage in JavaScript. If you would like to learn more check out our JavaScript page.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts