Chapter 05 โ Hoisting
๐ Definition
Hoisting is JavaScript's behavior of moving declarations (not initializations) to the top of their containing scope during the compilation phase, before code executes.
๐ Explanation
Before any code runs, the JS engine scans the code and registers all declarations:
| Declaration | Hoisted? | Initialized? |
|---|---|---|
var |
โ Yes | โ
to undefined |
let / const |
โ Yes | โ TDZ until line of declaration |
function (declaration) |
โ Yes | โ to the function |
function (expression) |
follows variable rules | depends on var/let/const |
class |
โ Yes | โ TDZ |
Temporal Dead Zone (TDZ) โ the period between entering the scope and the actual let/const/class declaration line. Accessing the variable in that window throws ReferenceError.
๐ป Code Example โ var Hoisting
console.log(a); // undefined (declaration hoisted, value not)
var a = 10;
console.log(a); // 10
// Equivalent to:
// var a;
// console.log(a);
// a = 10;
// console.log(a);๐ป Code Example โ let/const and the TDZ
console.log(b); // โ ReferenceError: Cannot access 'b' before initialization
let b = 20;
console.log(c); // โ ReferenceError
const c = 30;๐ป Code Example โ Function Declaration vs Expression
// Function DECLARATION โ fully hoisted
sayHi(); // "Hi!"
function sayHi() { console.log("Hi!"); }
// Function EXPRESSION assigned to var โ only var is hoisted
sayBye(); // โ TypeError: sayBye is not a function
var sayBye = function () { console.log("Bye!"); };
// Function EXPRESSION assigned to let โ TDZ
sayHello(); // โ ReferenceError
let sayHello = function () { console.log("Hello!"); };๐ป Code Example โ Arrow Functions
// Arrow functions are NOT hoisted like declarations
greet(); // โ ReferenceError
const greet = () => console.log("Hello");๐ป Code Example โ Hoisting Order
function test() {
console.log(x); // [Function: x]
var x = 10;
function x() {} // function declarations win the initial value
console.log(x); // 10
}
test();๐ Real-World Impact
- Always declare with
const/letto avoidvarhoisting surprises. - Place function declarations near the top of files for readability โ hoisting masks bad ordering.
- Linters (ESLint
no-use-before-define) catch most hoisting bugs.
๐ฏ Likely Interview Questions
- What is hoisting?
- What is the Temporal Dead Zone?
- Are arrow functions hoisted? โ No. They follow variable hoisting rules.
- What's the difference between function declarations and function expressions in terms of hoisting?
- Output prediction:
var a = 1; function foo() { console.log(a); var a = 2; } foo(); // undefined โ local `a` is hoisted and shadows the outer