Hoisting
πΉ What is Hoisting?β
- Hoisting is JavaScriptβs default behavior of moving declarations to the top of their scope (global or function scope).
- It means you can use variables/functions before they are declared in the code (though behavior depends on
var,let,const, or function type).
Check out the video and come back here
Video by Web Dev Simplified
https://www.youtube.com/watch?v=EvfRXyKa_GI
πΉ What Gets Hoisted?β
| Item | Hoisted? | Behavior |
|---|---|---|
var variables | β Yes | Hoisted but initialized as undefined. |
let & const variables | β Yes | Hoisted, but kept in Temporal Dead Zone (TDZ) until initialized. Using before declaration β β ReferenceError. |
| Function Declarations | β Yes | Hoisted fully (you can call them before declaration). |
| Function Expressions | β οΈ Partial | Variable is hoisted, but assignment happens later. If declared with var β undefined; with let/const β TDZ error. |
| Class Declarations | β Yes | Hoisted but in TDZ. Cannot access before declaration. |
πΉ Examplesβ
1. var Hoistingβ
console.log(a); // undefined (not error)
var a = 10;
console.log(a); // 10
π var a; is hoisted at the top, but value assignment (a=10) happens later.
2. let & const Hoisting (TDZ)β
console.log(b); // β ReferenceError
let b = 20;
console.log(c); // β ReferenceError
const c = 30;
π Both b and c are hoisted but kept in Temporal Dead Zone until their line of initialization.
3. Function Declaration Hoistingβ
sayHello(); // β
Works
function sayHello() {
console.log("Hello, World!");
}
π Entire function is hoisted, so you can call it before declaration.
4. Function Expression Hoistingβ
greet(); // β TypeError: greet is not a function
var greet = function () {
console.log("Hi!");
};
π var greet; is hoisted β undefined. At call time, itβs not yet assigned as a function.
5. Arrow Functions with let/constβ
sayHi(); // β ReferenceError
const sayHi = () => {
console.log("Hi there!");
};
π Hoisted but in TDZ β cannot use before declaration.
6. Class Declaration Hoistingβ
const obj = new Person(); // β ReferenceError
class Person {
constructor() {
this.name = "John";
}
}
π Classes are also hoisted but in TDZ like let/const.
πΉ Real-Time Example (Why It Matters)β
Example: Loading Configβ
// Use config before declaration
initializeApp();
function initializeApp() {
console.log("App started with mode:", mode);
}
var mode = "production";
Output:
App started with mode: undefined
π Here, mode is hoisted as var mode; but initialized as undefined when initializeApp runs.
This can cause bugs in production apps if developers expect the value.
β
Fix: Use let/const to avoid unexpected undefined.
πΉ Key Takeawaysβ
- Declarations are hoisted, not initializations.
- Use
letandconstto avoid bugs caused byvar. - Function declarations are hoisted completely.
- Function expressions & arrow functions depend on variable hoisting rules.
- Classes are hoisted but inaccessible before initialization (TDZ).