Hoisting
JavaScript moves declarations to the top of their scope during compilation (conceptually).
console.log(x); // undefined (not ReferenceError)
var x = 5;
console.log(y); // ReferenceError
let y = 5;
var vs let vs const
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Reassign | Yes | Yes | No |
Temporal Dead Zone (TDZ)
The period between entering scope and declaration where let/const cannot be accessed.
Interview Questions
Q: What gets hoisted?
vardeclarations (initialized as undefined)functiondeclarations (fully hoisted)let/const(hoisted but in TDZ)
Q: What's the output?
var a = 1;
function test() {
console.log(a);
var a = 2;
}
test(); // undefined
Local var a is hoisted inside test, shadowing the outer a.
Best Practice Answer
"Always use const by default, let when reassignment is needed, avoid var in modern code."