Variable Hoisting with var
Variables declared with var are hoisted to the top of their scope. Only the declaration is hoisted, not the assignment.
console.log(message); // undefined (not an error)
var message = "Hello!";
console.log(message); // Hello!
Try it Yourself โ
The interpreter sees the code above as:
var message;
console.log(message); // undefined
message = "Hello!";
console.log(message); // Hello!
Hoisting of let and const
let and const are hoisted but not initialized. Accessing them before declaration throws a ReferenceError due to the temporal dead zone.
// console.log(myLet); // ReferenceError
let myLet = 5;
console.log(myLet); // 5
// console.log(myConst); // ReferenceError
const myConst = 10;
console.log(myConst); // 10
Function Declaration Hoisting
Function declarations are fully hoisted โ both the name and the body. You can call them before they appear in the code.
console.log(add(2, 3)); // 5
function add(a, b) {
return a + b;
}
Function Expressions Are Not Hoisted
Function expressions assigned to variables follow the hoisting rules of the variable keyword used.
// console.log(subtract(5, 2)); // TypeError or ReferenceError
const subtract = function(a, b) {
return a - b;
};
console.log(subtract(5, 2)); // 3