JavaScript Hoisting

Javascript hoisting plays a vital role in the part of the declaration. The aim is to move all the declarations on top of the scope before code execution begins.

  • No matter where the functions and variables have located the scope of hoisting moves to the top regardless of their scope.
  • This in turn allows us to call the functions before even writing the functions in the code.

Enough talking let us clearly understand what it does:

g = 10; //assigning


var g; //declaration

Output: 10

  • so here we can get the basic idea of what we are talking about.
  • The keyword var is used to declare the variable g after the code execution of the assignment which took place before code execution.
  • Javascript can adapt and get the declared value regardless of the position of the scope.
  • Also, note that a variable must be declared else it will be considered as a globally declared variable.

Let us see another example:

The declaration is about no matter where we declare javascript takes it to top according to its account.
whereas when assigning it should be on top else we will get an undefined error.

var colour;

colour = 'blue'

Output: Undefined

Here we get undefined because of the way we assigned the variable value. 
the order matters for assigning.

var colour;

colour = 'blue'

Here for the same code let us try to print it after the assignment.


So the order matters for assigning the variable where we declare matters as javascript takes this as a priority of order in this case.

var sensei = 'minato namikaze'

Output: Undefined

Here it has been declared this has no problem right but the real problem is it is not defined on top as the assigning needs to be on top.

var sensei = 'Minato Namikaze'

Minato Namikaze

Now we can see that it get the priority of assignment and prints the variable.

Examples in functions:

Functions are also hoisted to the top.

function dosomething(){

Output: Hoisted

  • Here as we mentioned the functions are also hoisted to the top in javascript and don't take order into consideration.
  • So to conclude to make it easier we must always declare our variables at the top to make it easier to read.
Wed, 12/08/2021 - 14:18

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.