JavaScript Hoisting

Profile picture for user arilio666

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

console.log(g);

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.

console.log(colour);
var colour;

colour = 'blue'

Output: Undefined

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

console.log(colour);
var colour;

colour = 'blue'
console.log(colour);

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

Output:
undefined
blue

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

console.log(sensei)
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.

console.log(sensei)
var sensei = 'Minato Namikaze'
console.log(sensei)

Output:
undefined
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.

dosomething()
function dosomething(){
console.log('Hoisted')
}

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.