Hoisting is JavaScript's default behavior of moving function and variable declarations to the top of their scope before code execution. It means, 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.
x = 10;
y = 20;
console.log(x+y); // 30
var x;
var y;
Hoisting is not possible with variable initializations, only declarations are hoisted.
console.log(x+y); // undefined
var x = 10;
var y = 20;
Like variable hoisting, JavaScript compiler moves the function definition at the top.
console.log(Sum(10, 20)); // 30
var Total = function Sum(x, y) {
return x + y;
}
JavaScript compiler does not move function expression at the top. So, function hoisting in JavaScript is only possible with definition.
console.log(Sum(10, 20)); // 30
function Sum(x, y) {
return x + y;
}