HOISTING

Hoisting

Hoisting is JavaScript’s default behaviour of moving variables and function declarations to the top of the current scope before code execution.

Inevitably, this means 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.

Note that hoisting only moves the declaration, while assignments are left in place.

  • Variable Hoisting
  • Function Hoisting

Variable Hoisting :

JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be undefined.

Initializations using let and const will not hoisted.

Example :

  • If you try to use a variable before declaration and initialization, the output will be variable not defined.
  • var x = 5;
    console.log(age); // ReferenceError: age is not defined
  • If you declare a variable after using it, the output will be undefined.
  • var x = 5;
    console.log(age); // Prints: undefined
    var age;
  • In above example, you can notice that how you got undefined because the variable age moved to top of the current scope.
  • If you declare and initialize a variable after using it, still the output will be same as previous example which is undefined.
  • console.log(age); // Prints: undefined
    var age = 15;
  • You can notice in above example(it has printed undefined instead of 15). So, that means declaration gets hoisted not initialization.

Function Hoisting :

Function declaration or statement gets hoisted where as function expression doesnt get hoisted in javascript as shown in below example.

calculateAge(1995);
function calculateAge(year) {
console.log(2020-year); // Prints: 25
}
age(1995); //Prints: age is not a function
var age = function (year) {
console.log(2020 - year);
};

In the above example, function is called before assigning the function. Here, whole function will be stored in global memory before code execution, where ever we call the function, it will execute.