JavaScript Basic
What is Hoisting in JavaScript?
What is Hoisting?
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope before code executes.
var Hoisting
var declarations are hoisted, but initializations are not:
console.log(a); // undefined (no error)
var a = 5;
console.log(a); // 5
// Equivalent to:
var a; // hoisted to top
console.log(a); // undefined
a = 5;
let and const — Temporal Dead Zone (TDZ)
let and const are hoisted but cannot be accessed before declaration — this is the Temporal Dead Zone:
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 10;
Function Declaration Hoisting
Function declarations are fully hoisted (including their body):
foo(); // ✅ 'Hello' (callable before declaration)
function foo() {
console.log('Hello');
}
Function Expressions Are NOT Hoisted
bar(); // ❌ TypeError: bar is not a function
var bar = function() {
console.log('World');
};
Summary
| Declaration | Hoisted | Initial Value | TDZ |
|---|---|---|---|
var |
✅ | undefined |
❌ |
let |
✅ | uninitialized | ✅ |
const |
✅ | uninitialized | ✅ |
| Function decl. | ✅ | Full function | ❌ |
| Function expr. | Variable only | undefined |
— |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
