JavaScript Hoisting

JavaScript Hoisting
In JavaScript Hoisting 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).
Hoisting with var
Variables declared with var are hoisted but initialized as undefined.
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).
Function Hoisting
Function Declarations are fully hoisting:
Function Expressions are NOT fully hoisting:
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
letandconstto avoid confusion - Declare variables at the top of their scope
- Avoid relying on hoisting behavior in real projects
