Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope, before the code has been executed.
In JavaScript, both var
and function
declarations are hoisted. However, the initializations are not.
console.log(myVar); // undefined
var myVar = 5;
console.log(myVar); // 5
In this example, the variable myVar is hoisted, but its initialization with the value 5 is not. Therefore, the first console.log prints undefined.
Function declarations are hoisted, with both their name and body.
hoistedFunction(); // Output: This function has been hoisted.
function hoistedFunction() {
console.log('This function has been hoisted.');
}
Here, the entire function hoistedFunction is hoisted, so calling the function before its declaration in the code does not cause an error.
ES6 introduced two new types of variable declarations: let and const. They are also hoisted, but accessing them before the declaration leads to a Reference Error.
console.log(myLetVar); // ReferenceError
let myLetVar = 5;
Hoisting can cause unexpected results, so it's generally a good idea to always declare your variables at the top of their scope.