Rathik's dev blog

What is Javascript Hoisting ?

Macbook pro on brown wooden table
Published on
/2 mins read/---

Javascript Hoisting

Img Credit : Vitolda Klein

Introduction

When you load your javascript to browser, javascript engine executes it and create global execution context. That has two phases.

  • Creation
  • Execution

Hosting happens on when the phase on creation mode, the javascript engine moves the Variable and Function declaration to the top of the scope.

Variable Hoisting

Lets run the Example : 1 code first.

Example : 1

console.log(name);   // undefined
var name = "JavaScript";

Hope it doesn't make an error and showing "undefined". Cause Javascript moves the Variable declaration top of the scope.

okay, just run Example : 2 code

Example : 2

var name;
console.log(name);   // undefined
var name = "JavaScript";

I think , still you got the same result on example two.

Its meaning during the creation phase, var name automatically declare to the top & initialize value "undefined"

Function Hoisting

Lets run the Example : 1 code first.

Example : 1

let result = add(20, 30);
console.log(result);
 
function add(a, b) {
  return a + b;
}

Like as Variable Javascript engine hoisted the function to the top.

Example : 2

function add(a, b) {
  return a + b;
}
let result = add(30, 30);
console.log(result);

If you compare the output both are giving same result. During the creating phase the function add automatically move to the top of scope.

Note :

  • Unlike var, they are not initialized with a default value while hoisting.
  • They cannot be read/written until they have been fully initialized.
  • Javscript hoisting not working arrow function and expression.

If there has any issues or wrong instruction, please feel free to contact with me by comments or mail: hello@rathik.dev