RMRM Full Stack & AI Engineer · All guides · Roadmaps
Languages · guide

Hoisting in JavaScript

Hoisting is a JavaScript engine behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before any code executes. Understanding hoisting is essential for writing predictable, bug-free JavaScript.

What Is Hoisting?

During the compilation phase, the JavaScript engine scans your code and allocates memory for variable and function declarations before execution begins. This makes it appear as though declarations are physically 'moved' to the top of their scope. Only declarations are hoisted — initializations and assignments are not.

Function Hoisting

Function declarations are fully hoisted, meaning both the declaration and the function body are available before the line where they appear. This allows you to call a function before it is written in the source code. Function expressions (e.g., const fn = function(){}) are NOT fully hoisted — only the variable binding is, not the function value.

var Hoisting

Variables declared with var are hoisted to the top of their function scope and initialized with the value undefined. Accessing a var variable before its assignment line will return undefined rather than throwing an error. This silent behavior is a common source of bugs and is one reason var is generally avoided in modern JavaScript.

let and const Hoisting

Variables declared with let and const are also hoisted, but they are NOT initialized — they remain in a 'Temporal Dead Zone' (TDZ) from the start of the block until the declaration is reached. Accessing them before their declaration throws a ReferenceError. This strict behavior makes bugs easier to catch and is why let and const are preferred over var.

Key Gotcha: Temporal Dead Zone

The Temporal Dead Zone exists from the opening of a block scope until the let or const declaration is evaluated at runtime. Even though the variable technically exists in memory, any read or write before the declaration line causes a ReferenceError. Always declare let and const variables at the top of their block to avoid TDZ-related bugs.

Best Practices

Declare all variables at the top of their scope to make hoisting behavior explicit and code easier to reason about. Prefer const by default, use let when reassignment is needed, and avoid var entirely in modern codebases. Use function declarations when you need hoisting intentionally, and function expressions or arrow functions when you want stricter control over availability.

Go deeper with an AI tutor that teaches this in context — and quizzes you on it.
Open the app — free to start

© RM Full Stack & AI Engineer · All guides · Roadmaps · Open the app