Hoisting in Javascript

Hoisting in Javascript

In this article, we will see Hoisting along with some examples.

start

Usually, people say in hoisting means variables and function declarations are physically moved to the top of your code, but this is not in fact what happens. According to MDN docs:

The variable and function declarations are put into memory during the compile phase but stay exactly where you typed them in your code.

If you are not comfortable with execution context and callstack I suggest you read this article before going further: how-javascript-works.

Let us now understand hoisting more with examples:

Example 1: Try to guess the output of the following script what do you think it will be?

console.log(x)
var x=7;

Even though we call the variable "x" is used before its declaration, we won't see any error due to the concept of hoisting. When we ran this code execution will take place in two steps, during the creation of the global execution phase the js engine will allocate memory for variable x and assign the initial value as undefined.

Screenshot from 2021-06-10 17-25-43.png

Example 2:

Like variables, functions are also hoisted.

Screenshot from 2021-06-10 17-47-28.png

Now as we know functions are stored along with code in the memory during the creation of global execution phrase.

Screenshot from 2021-06-10 17-49-35.png

Example 3:

Now, let's see the case of a function expression.

Screenshot from 2021-06-10 18-03-52.png

The function expression behaves as variables and its initial value is undefined during the creation of the global execution phase.

Example 4 Now let us see the case of arrow functions

Screenshot from 2021-06-10 18-23-44.png

The arrow function behaves just like variables and assigns the initial value as undefined.

Screenshot from 2021-06-10 18-26-48.png

Example 5:

Now let us see let, const, var.

Screenshot from 2021-06-10 18-31-25.png

So, are let and const not hoisted?

Well, the answer is different let and const are hoisted in javascript, while var is initialized with undefined let and const remains uninitialized. They will only be initialized during runtime. This means we cant access a value before its value is evaluated. This is called the Temporal Dead zone.

Summary

  • var,let,const-hoisted
  • arrow functions-not hoisted
  • functions-hoisted
  • function expression-not hoisted

That's it for this article.

Thanks