Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope (script or function) before the code is executed.
đź§ Think of it as:
“JavaScript scans your code for variable and function declarations before running it, and moves those declarations to the top.”
đź§Ş Example 1: Variable Hoisting
console.log(x); // undefined
var x = 10;
You’d think it would throw an error, but nope — output is undefined because:
var x; // declaration is hoisted
console.log(x); // undefined
x = 10; // assignment stays in place
âť— var vs let / const
console.log(y); // ❌ ReferenceError
let y = 5;
With let and const, declarations are hoisted, but not initialized. They stay in a Temporal Dead Zone (TDZ) until the line where they’re declared.
⚙️ Example 2: Function Hoisting
greet(); // âś… Works!
function greet() {
console.log('Hello!');
}
👉 Entire function declarations are hoisted (both name and body).
BUT…
sayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function() {
console.log('Hi!');
};
Because here, only the variable sayHi is hoisted (with undefined), not the function.
📝 Summary
| Feature | Hoisted? | Initialized? | Accessible Before Declaration? |
|---|---|---|---|
var |
âś… Yes | âś… Yes (with undefined) |
âś… Yes (but undefined) |
let / const
|
✅ Yes | ❌ No | ❌ No (TDZ error) |
| Function Declaration | âś… Fully | âś… Yes | âś… Yes |
| Function Expression (var) | ✅ var only | ❌ No | ❌ No (TypeError) |
\
Top comments (0)