Hoisting Phenomena! Every Javascript dev should know.๐Ÿค

Struggling to understand what hoisting is? This article is the rescue!

ยท

2 min read

Hoisting Phenomena! Every Javascript dev should know.๐Ÿค

First, let's get it clear that hoisting is not any concept but it's a phenomenon in javascript. It tells you how javascript behaves while accessing the variables during the runtime. Hmm... Now let's take an example below -

console.log(x);
var x = 10;

What must be the output for this code? The answer is

undefined

But Why? This is because of hoisting. The variable x is being hoisted. That means it is accessed before its initialization. Now let's understand how javascript runs behind the scene for the above code.

Execution Context

The javascript code execution has 2 phases. First one is called as memory allocation phase and the second is the code execution phase. When the code gets compiled it forms a global execution context where all the code will get executed. All the variables are allocated some space in memory and are assigned a placeholder as undefined during the memory allocation phase.

By this, we can now say from the above code that variable x has been allocated memory and got a placeholder as undefined in the memory allocation phase. Now that the memory is assigned to the variable x, it's time to execute the code inside the code execution phase.

Javascript will point to the first line of the code to execute. Here, x is still not been assigned any value and has a placeholder as 'undefined'.

console.log(x);

so, it will execute it and give the output as undefined in the console. This is why we have our output as undefined. And this is what hoisting is.

Now, the next line is executed, and here variable x gets assigned with value 10. But it will just reside inside the memory.

var x = 10; // x is assigned a value as 10

When you print the value of x after this, you can see the value is now 10.

console.log(x);
var x = 10;
console.log(x);

undefined

10

Note - let and cost cannot be accessed before its initialization. It is stricter than the var and has a separate scope from the global scope. During the memory allocation phase let and const variables still get undefined as a placeholder and are hoisted but they are in a different scope and cannot be accessed before initialization. The time between the memory allocation of let or const variables till their assignments to any value is called a Temporal Dead Zone!

I hope this has helped you understand hoisting in a simpler way. If you have any doubt please comment on the article or connect with me on Linkedin. Also, any feedback is welcomed for improvements.

Did you find this article valuable?

Support Code Craft - Fun With Javascript by becoming a sponsor. Any amount is appreciated!

ย