What Is Hoisting?
In JavaScript, hoisting is the default behavior of moving variable and function declarations to the top of their containing scope (script or function). Only declarations are hoisted—not the assignments.
This means that variables and functions can be used before they are declared, but their values may not be accessible if they are assigned after the usage.
How Hoisting Works
- Variable Declarations:
Variables declared using var are hoisted, but their value remains undefined until the assignment occurs.
Variables declared with let and const are hoisted but are placed in a temporal dead zone (TDZ) and cannot be accessed until declared. - Function Declarations:
Function declarations are fully hoisted, meaning you can call the function before declaring it. - Function Expressions and Arrow Functions:
Function expressions and arrow functions are not hoisted like function declarations. They behave like variables, so they are undefined until the assignment occurs.
Examples of Hoisting
Example 1: Variable Hoisting with var
console.log(a); // Output: undefined
var a = 10;
console.log(a); // Output: 10
Explanation:
- The declaration var a is hoisted to the top.
- The assignment a = 10 happens later, so the initial value is undefined.
Example 2: Hoisting with let and const
console.log(b); // Uncaught ReferenceError: Cannot access 'b' before initialization
let b = 20;
console.log(c); // Uncaught ReferenceError: Cannot access 'c' before initialization
const c = 30;
Explanation:
- Variables declared with let and const are hoisted but remain in the temporal dead zone until their declaration is encountered.
Example 3: Function Declaration Hoisting
greet(); // Output: Hello, world!
function greet() {
console.log("Hello, world!");
}
Explanation:
- Function declarations are fully hoisted, so you can call the function before its declaration in the code.
Example 4: Function Expression Hoisting
sayHello(); // Uncaught TypeError: sayHello is not a function
var sayHello = function() {
console.log("Hello!");
};
Explanation:
- The variable sayHello is hoisted but initialized as undefined. Since it’s a function expression, it cannot be called before its assignment.
Differences Between var, let, and const in Hoisting
Feature | var | let and const |
---|---|---|
Hoisting Behavior | Hoisted with undefined | Hoisted but in TDZ |
Temporal Dead Zone | Not Applicable | Applicable |
Re-declaration | Allowed | Not Allowed |
Key Takeaways
- Hoisting is a JavaScript mechanism that moves declarations to the top of their scope.
- Only declarations are hoisted; assignments are not.
- Function declarations are fully hoisted, while function expressions are not.
- let and const declarations are hoisted but remain inaccessible until declared due to the temporal dead zone.