JavaScript hoisting is a fundamental concept that can sometimes confuse even experienced developers. Understanding it thoroughly helps avoid common pitfalls and write cleaner code. This post breaks down hoisting in variables, functions, and classes, explains the Temporal Dead Zone (TDZ), and highlights best practices to manage them effectively.
What is Hoisting?
Hoisting refers to JavaScript’s behaviour where declarations (not initializations) of variables, functions, and classes are moved—"hoisted"—to the top of their current scope before code execution. This means you can sometimes use variables or functions before you declare them in the code.
Hoisting in Variables: var vs let vs const
var declarations are hoisted and initialized with undefined. So accessing them before the declaration gives undefined, not an error.Temporal Dead Zone (TDZ) Explained
Why reference errors occur:
JavaScript knows about x but forbids using it until its definition to avoid unpredictable behaviours.Function Hoisting: Declarations vs Expressions
Class Hoisting
Execution Context: Hoisting + TDZ + Errors
var vs let vs const in Practice
Avoid Hoisting & TDZ Issues: Best Practices
- Always declare variables at the top of scopes to avoid confusion.
- Prefer const and let over var for clearer scoping and TDZ safety.
- Avoid calling functions before declaration when using function expressions.
- Use function declarations if you need hoisting, but understand scope rules.
- Write code to minimise dependency on hoisting behaviour — it improves readability and reduces bugs.
- Initialise variables at declaration whenever possible.