Computer >> Computer tutorials >  >> Programming >> Javascript

Function hoisting in JavaScript


Hoisting is a JavaScript technique which moves variables and function declarations to the top of their scope before code execution begins. Within a scope no matter where functions or variables are declared, they're moved to the top of their scope.

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

Example

console.log(functionBelow("Hello"));
function functionBelow(greet) {
   return `${greet} world`;
}
console.log(functionBelow("Hi"));

Output

Hello world
Hi world

Note that the function declaration was after it was called but was still called. This was possible due to function hoisting.

Also note that it doesn't work when you assign functions like variables.

console.log(functionBelow("Hello"));
var functionBelow = function(greet) {
   return `${greet} world`;
}
console.log(functionBelow("Hi"));

This will fail with an error: functionBelow is not a function

If you remove var, it'll fail with the error: functionBelow is not defined

Note that when it was declared with var, it was hoisted as a variable in the context. But it still remained undefined. This is known as variable hoisting. Due to this property, anonymous and arrow functions are never hoisted in JavaScript.