Categories
Javascript

Javascript Hoisting

In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
It allows us to call functions before even writing them in our code.

Note: JavaScript only hoists declarations, not the initialisations.

Example1: Function Hoisting
alert(Sum(5, 5)); // 10
function Sum(val1, val2){
  return val1 + val2;
}
Example2: Function Hoisting
Add(5, 5); // error
var Add = function Sum(val1, val2){
  return val1 + val2;
}
Example3: Function Hoisting
alert(UseMe);
var UseMe;
function UseMe(){
  alert("UseMe function called");
}