Hoisting in Javascript

Hoisting-blog-img.jpg

Originally Posted On...

Javascript is a high-level programming language. It has dynamic typing and an interpreted language, not a compiled language. It's used for adding interactive behavior to web pages and abstracting away from how browsers work.

Javascript is a high-level programming language. It has dynamic typing and an interpreted language, not a compiled language. It's used for adding interactive behavior to web pages and abstracting away from how browsers work.

We need to understand how Javascript is functioning in order to write the javascript code in a proper way but there are some weird parts also that you need to understand and when you understand, there will be an Aha moment for you.

So let's enjoy this journey together.

Before we start we need to understand how javascript is working:

There are two phases of the javascript code execution context.
Creation phase- In this phase, the setup of variables and functions in memory is to be done.
Execution phase- In this phase, code is to be run line by line and executed in such a manner that the computer understands the code.

Here are a few interesting things:
You can call variables and functions before declaring them, yes you heard that right!!

In javascript, you can define variables using var, let, and const keywords.

With var keyword: hosting 1.PNG

This happens because of hoisting.

Now, what is Hoisting?
Hoisting is all about moving all the declarations at the top of the scope before code execution and this happens in the first phase of code execution. As stated earlier in the creation phase javascript allocates the memory to all variables and functions present in the program. If variables are declared with the var keyword stored with the value undefined and the function is stored with all the code they have in their body.

I’m sure that you know that Undefined and Null are data types in javascript and you don’t have confusion between undefined and not defined errors.

With let and const:
hosting 2.PNG

In javascript, let and const are also hoisted but they are temporary in the dead zone. So you can’t access them before assigning value to them.

With Functions:
hosting3.PNG

Functions are fully hoisted so we can call them before their declaration.

Function expressions and class expressions are not hoisted.

I hope now you are clear about how hoisting is working in javascript.

Conclusion:
At first glance, it looks weird but when you understand how this concept works this will be fun for you and it will be helpful with your javascript journey.

Get In Touch With Us To Know More...