JavaScript Hoisting Explained
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope before code execution.
This means you can use functions and variables before declaring them – but with important rules!
1. Hoisting with var
var declarations are hoisted and initialized with undefined.
Example:
console.log(x); // undefined (not error)
var x = 10;
Output
Explanation:
JavaScript interprets it like this:
var x; // Hoisted
console.log(x);
x = 10;
Use let or const instead of var to avoid hoisting bugs.
2. Hoisting with let and const
let and const are hoisted but not initialized. Accessing them before declaration causes a ReferenceError due to the Temporal Dead Zone (TDZ).
Example:
console.log(a); // ReferenceError
let a = 5;
Output
3. Hoisting with Functions
Function declarations are fully hoisted, so you can call them before they are defined.
Example:
sayHello(); // Works
function sayHello() {
console.log("Hello!");
}
Output
Function Expressions Are NOT Hoisted
Function expressions using var, let, or const are not hoisted like function declarations.
Example:
greet(); // TypeError or ReferenceError
var greet = function () {
console.log("Hi!");
};
Output
Only function declarations (not expressions) are hoisted this way.
Summary Table – JavaScript Hoisting
Type | Hoisted? | Initialized? | Can Use Before Declaration? |
---|---|---|---|
var | Yes | undefined | But risky |
let / const | Yes | No (TDZ error) | ReferenceError |
Function Declaration | Yes | Yes | Safe to use early |
Function Expression (var) | Yes | undefined | TypeError |
Function Expression (let/const) | Yes | No | ReferenceError |