Hoisting in Javascript (functions and variables)

Hoisting is the process of putting all functions and variables declaration in the memory during compile phase. Hoisting happened on every execution context.

 JavaScript only hoists declarations, not the initializations.

Important points about Hoisting

  • In Javascript functions are fully hoisted. So functions can be accessed from anywhere.


  /**
     function can called before it's declaration
   */

a()
function a() {
    console.log("Function Declarations .....");
    return 1;
}
a()

  /**
     function can called after it's declaration
   */

Note: Hoisting allows us to call functions before even writing them in our code.

  • var variables are hoisted and initialized with undefined values.

var x=5;
console.log(x);

  /**
     x can be able to access after it's declaration.
   */

  • let and const are also fully hoisted and not initialized with any value.

const y=5;
let z=7;
  /**
     y and z can be able to access after declaration
   */

console.log(y);
console.log(z);
  • If we are going to access a var variable before it’s declaration then it will be undefined.


  /**
     x can't be able to access before declaration if we want to access
     it before then get undefined 
   */

console.log(x);
var x=5;
  • If we are going to access let and const variable before its declaration then it will throw a reference error.


  /**
     y and z can't be able to access before declaration if we want to access
     it before then it will throw reference error 
   */
console.log(y)
console.log(z); const y=5; let z=7;