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) |
\