Hoisting In Javascript.

Hoisting In Javascript.

confusing and useful which is hoisting.

Hey readers, This is another blog regarding javascript in which you will know about hoisting in javascript.

What is hoisting?

According to mdn: JavaScript Hoisting refers to the process whereby the compiler allocates memory for variable and function declarations prior to execution of the code.

Variable hoisting:

  • Before starting to understand hoisting let's understand how javascript works with variables behind the scenes.
console.log(name);
var name="javascript";

Output: hsThirdOP.png

  • Surprising right, we accessing the name without declaring it and it will not show an error like "variable name is not defined". In js whenever we declare any variable with keyword var, it will be assigned by undefined before compiling a single line of code.

Example:

name="javascript";
console.log(name);
var name;

Output:

Screenshot from 2021-08-21 12-29-42.png

  • In js, wherever you declared the variables and function, they are moved to the top of code and it's called declarations are hoisted in javascript. So that's why even if the declaration of name is at the end it will be accessible.

  • Only declarations are hoisted in js, not initialization.

Function hoisting:

Scenario 1: using normal function

printMethod();    // function call
function printMethod(){      //  function declaration
      console.log("inside the method");
}

Output:

Screenshot from 2021-08-21 13-02-11.png

  • As variables and function declaration are hoisted, we can call the function before its declaration and it will no show any error like "function not defined".

Scenario 2: using arrow function

printMethod();
var printMethod = () => {
      console.log("inside the method");
}

Output:

Screenshot from 2021-08-21 13-27-49.png

  • In the above example, we are storing the function into the printMethod variable. So we can call it variable initialization, and initialization is not hoisted in javascript so that's why it showing an error.

Scenario 3: using anonymous function

printMethod(); 
var printMethod = function () {
      console.log("inside the method");
}

Output: Screenshot from 2021-08-21 13-27-49.png

  • In the above example, we are storing an anonymous function to the variable. so it will become variable initialization and in js, only declarations are hoisted and initialization is not so it will give an error.

Note: Initializations are not hoisted even if it initialized using the var keyword.

Conclusion:

  • Only declarations are hoisted not initialization.

So that's it in this blog, I hope you understand about hoisting. feel free to give suggestions and feedback.

jbue.gif