Hoisting in Javascript

Hoisting in Javascript

ยท

2 min read

Before declaring any variable and function if we try to access it, That is called hoisting

To understand hoisting you need to understand the execution context. I highly encourage you to have a look at this blog and at least understand the memory execution and code execution part.

In the billow example, I declare a variable and function. and after that I accessed it and get the expected output 10 and 2, This is the Normal case without Hoisting

// Example One
var month = 10;

function getDay(){
  console.log(3)
}
console.log(month)
getDay();
// ------------- output ----------------
10
3

Now In this billow example two we try to access the both variable and function before declaring it, and for variable we got undefined and for function we got the correct output 3

// Example Two
console.log(month)
getDay();

var month = 10;
function getDay(){
  console.log(3)
}
// ------------- output ----------------
undefined
3

If you understand execution context then you know

javascript assigns memory in key-value pair. In the case of variables The key is the variable name and the value is undefined, and In the case of functions, the key is the function name and the value is the whole codeBase under the function query brackets.

in the code execution phase code executes line by line.

In case of our example two, in memory execution => first variable month got undefined and getDay() got the whole function code base

and Then in code execution => the variable month got the value 10 and when the function call happened then code under the function got executed

Attention Please :

In the memory allocation phase,a got undefined and in the code execution phase before javascript assign a to 10 we trying to access a, and that's why we got undefined

Ok but then how function gives the correct value

Because in the memory allocation phase key is function name and the value is the whole code base under the function. That's why when we call the function before declaring it, javascript executed the whole code base under the function and we got the correct output

Thank you for reading ๐ŸŽ‰๐ŸŽ‰ I hope it will help you in your javascript journey.

Did you find this article valuable?

Support Rohan Malo's blog by becoming a sponsor. Any amount is appreciated!

ย