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.
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.
var x = 5;
console.log(age); // ReferenceError: age is not defined
var x = 5;
console.log(age); // Prints: undefined
var age;
console.log(age); // Prints: undefined
var age = 15;
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.