Hoisting in Javascript.

Shivani Nalawade
2 min readApr 13, 2020

Definition: Hoisting is one of the term used in Javascript where the declaration of variable and function are moved to the top of their scope before code execution.

JavaScript Hoisting

“Hoisting is JavaScript’s default behavior of moving declarations to the top and this is called hoisting”

fig:Variable and Function Hoisting

“Only variable declarations move to the top, not the initialization”

Example 1:

var s=5;

console.log(s);

//Output-5

  • In the above example the variable is declared and initialized at top of the program so, the output is 5.

Example 2

var s;

console.log(s);

s=5;

//Output-undefined

  • Output is undefined, because variable is assign at the top of the program but initialized at the bottom of the program and the hoisting is done only on declaration part.

Example 3

s=5;

console.log(s);

var s;

//Output-5

  • The initialization of variable is at top of the program and the variable is declared at bottom of the program and the output is 5 because of Hoisting (All the declaration and declared variable or function moved at Top).

Let’s look at how function scoped variables are hoisted.

JavaScript compiler moves the function definition at the top in the same way as variable declaration.

“Functions definition moves first before variables”

Example 1

alert(Sum(5, 5));

function Sum(val1, val2)
{
return val1 + val2;
}

//Output-10

  • This is a example of function hoisting. In the above example the Function definition is declared and initialized at top of the program so, the output is 10.
  • The function declaration may be anywhere in program but at compile time it moved at top of program.

Example:

doHoist()
function doHoist(){
console.log(‘Hoist’);
}
functionAssignedToVariable()
var functionAssignedToVariable = function(){
console.log(‘inside a function variable’);
}

  • Line 2 spits out the expected ‘Hoist’ response because the function declaration was hoisted to the top of the code.
  • Line 8 spits out an err b/c even though the variable declaration WAS hoisted, the definition was NOT.

To better understand this concept please do watch the below video.It will resolve your all doubts:

--

--