Hoisting is the JavaScript behavior in which declarations are processed before any code in a scope executes, so that functions and variables are known to the engine from the start of their scope rather than from the line where they are written. In Browser JavaScript, hoisting explains why a function can be called above its definition, why a var variable reads as undefined before assignment, and why let and const throw a ReferenceError when touched too early.
The name suggests that code is physically moved to the top, but nothing is moved. The engine performs a creation phase for every scope, records each declared name in an environment record, and only then runs the statements in order. Understanding this two-phase model is essential for reading legacy scripts, debugging initialization errors and writing predictable modules for the web.
How the engine creates bindings before execution
Hoisting results from the way the ECMAScript specification sets up an execution context. Before a script, module or function body runs, the engine scans it and creates a binding for every declaration in the relevant environment record. Only after this declaration instantiation step does it evaluate statements from top to bottom.
What differs between declaration kinds is the initial state of the binding. A function declaration is created and initialized with the complete function object immediately. A var binding is created and initialized to undefined. A let, const or class binding is created but left uninitialized, and any access before its declaration line runs throws an error.
The following table summarizes how each declaration form behaves during the creation phase and what happens when code reads the name early.
| Declaration | Binding created early | Initial value | Early access result |
|---|---|---|---|
| Function declaration | Yes | Full function object | Call works normally |
| var | Yes | undefined | Returns undefined |
| let | Yes | Uninitialized | ReferenceError |
| const | Yes | Uninitialized | ReferenceError |
| class | Yes | Uninitialized | ReferenceError |
| Function expression in var | Variable only | undefined | TypeError when called |
| import | Yes, module scope | Live binding linked before run | Works after linking |
The temporal dead zone of let, const and class
The temporal dead zone (TDZ) is the period between the start of a scope and the point where a let, const or class declaration is evaluated. During the TDZ the name is already bound in the scope, which is why it shadows any outer variable of the same name, yet it cannot be read or written.
The TDZ is defined by time, not by position in the source. A function declared above a let may safely reference that variable if the function is only called after the declaration runs. Conversely, calling the same function before the declaration executes produces a ReferenceError, because the binding has not yet left the dead zone at that moment.
A frequent surprise is shadowing inside a block: if a block declares let count on its last line, any earlier use of count in that block refers to the uninitialized inner binding, not to an outer count. The typeof operator, which normally returns "undefined" for unknown names, also throws inside the TDZ.
How scope type affects hoisting
Hoisting always happens to the top of the declaring scope, and the scope itself depends on the keyword. var is function-scoped and ignores block boundaries, while let, const and class are block-scoped. Function declarations inside blocks follow block scoping in strict mode but have historical web compatibility semantics in sloppy scripts.
The next table shows where each binding lives and how it interacts with the browser’s global object.
| Declaration | Scope unit | Creates window property in classic script | Redeclaration in same scope |
|---|---|---|---|
| var | Function or script | Yes | Allowed silently |
| let | Block | No | SyntaxError |
| const | Block | No | SyntaxError |
| Function declaration | Function, or block in strict mode | Yes at top level | Allowed, last one wins |
| Any declaration in an ES module | Module | No | Depends on keyword |
In a classic script element, top-level var and function declarations become properties of window, which can collide with browser globals such as name or status. In ES modules, top-level declarations stay in module scope, and modules run in strict mode automatically, which removes the most confusing hoisting edge cases.
Function declarations compared with function expressions
Only function declarations are hoisted with their body. A function expression or an arrow function assigned to a variable follows the rules of that variable: with var the name exists but holds undefined, and with const it sits in the TDZ. The distinction determines whether calling before definition works.
This table compares the common ways to define a function and the result of invoking each one above its definition.
| Definition form | Example | Call before definition | Typical use |
|---|---|---|---|
| Function declaration | function init() {} | Works | Top-level helpers, readable ordering |
| var with expression | var init = function () {} | TypeError: not a function | Legacy code |
| const with expression | const init = function () {} | ReferenceError | Modern modules |
| const with arrow function | const init = () => {} | ReferenceError | Callbacks, event listener handlers |
| Class declaration | class Widget {} | ReferenceError | Components and models |
Many teams deliberately choose const with arrow functions so that the TDZ enforces define-before-use ordering. Others prefer declarations so that a file can present high-level logic first and helper functions below it. Both styles are valid when applied consistently.
Common mistakes and how to avoid them
Most hoisting bugs come from assuming source order equals initialization order. The table below lists recurring symptoms in browser code, their underlying cause and a reliable fix.
| Symptom | Cause | Fix |
|---|---|---|
| Variable reads undefined unexpectedly | var hoisted without value | Use let or const and declare first |
| ReferenceError: cannot access before initialization | Access inside the TDZ | Move the declaration above first use |
| Loop callbacks all see the final index | Single function-scoped var | Use let for a per-iteration binding |
| TypeError: x is not a function | Expression assigned to var called early | Use a declaration or reorder calls |
| Global value overwritten by a script | Top-level var on window | Use ES modules or block scope |
| Inner variable hides outer one too early | Block-level shadowing in TDZ | Rename or restructure the block |
- Enable strict mode or ES modules to remove sloppy-mode function hoisting quirks.
- Configure linters with rules such as no-use-before-define and no-var.
- Declare variables at the top of their block to make initialization order visible.
- Avoid relying on hoisting for circular imports, because a module may read a binding still in its TDZ.
In simple terms
Before JavaScript runs a piece of code, it first reads through it and makes a list of every name that will be used, like a teacher taking attendance before the lesson starts. That first pass is what people call hoisting.
Functions written with the function keyword are fully ready after that pass, so they can be used anywhere in their area. Names created with var are on the list but empty for now. Names created with let and const are on the list but locked until their line is reached, and touching them early causes an error. The practical lesson is simple: declare things before using them, and the code will behave as it reads.
A practical example
A front-end developer maintains an older product page that loads several classic scripts. A new script adds var name = 'promo'; at the top level, and the navigation menu suddenly displays the wrong label. Because the var declaration is hoisted into the global scope of the classic script, it overwrites window.name, a browser property that another script reads to restore state.
While fixing it, the developer also finds a click handler that reads var selected and logs undefined because the assignment happens later in the file. After converting both files to ES modules, replacing var with const and let, and moving declarations above their first use, the linter flags two more use-before-define cases. The result is a page with no global collisions and errors that surface during development instead of silently producing wrong values in production.