JavaScript Hoisting
β JavaScript Hoisting
Hoisting is JavaScriptβs default behavior of moving variable and function declarations to the top of their scope before execution.
This means you can use variables and functions before declaring them (but with rules).
πΉ 1οΈβ£ Hoisting with var
Variables declared with var are hoisted but initialized as undefined.
πΉ 2οΈβ£ Hoisting with let and const
let and const are hoisted but NOT initialized.
Accessing them before declaration causes an error because they are in the Temporal Dead Zone (TDZ).
πΉ 3οΈβ£ Function Hoisting
β Function Declarations are fully hoisted:
β Function Expressions are NOT fully hoisted:
β οΈ Arrow Functions behave like function expressions:
π§ Summary Table
| Declaration Type | Hoisted? | Initialized? | Can Use Before Declaration? |
|---|---|---|---|
var |
β Yes | undefined |
β Yes (but undefined) |
let |
β Yes | β No (TDZ) | β No |
const |
β Yes | β No (TDZ) | β No |
| Function Declaration | β Yes | β Yes | β Yes |
| Function Expression | β Yes | β No | β No |
| Arrow Function | β Yes | β No | β No |
π― Best Practices
β Use let and const to avoid confusion
β Declare variables at the top of their scope
β Avoid relying on hoisting behavior in real projects
