« All posts

How JavaScript Hoisting Actually Works Under the Hood

Hoisting isn't code movement — it's memory allocation. A technical breakdown of how var, let, const and functions behave inside the JS engine.

The common claim that JavaScript 'moves declarations to the top of the file' is technically inaccurate. In reality, before executing any code, the engine runs a memory creation phase where it scans and allocates space for every variable and function, then proceeds to an execution phase where code runs line by line. Hoisting is simply the observable effect of this two-pass model.

This distinction explains the different behaviors across declaration types. Variables declared with var are auto-initialized to undefined during the memory phase, so accessing them early returns undefined instead of throwing. Function declarations are stored in memory with their entire body, making them callable even before their point of definition. Function expressions, however, only hoist the variable container, not the assigned function—calling them early throws a TypeError. let and const are also hoisted, but left uninitialized in the so-called Temporal Dead Zone, where any access before the actual declaration line triggers a ReferenceError.

The piece also walks through Execution Contexts and the Call Stack, showing how engines like V8 or SpiderMonkey process a full script step by step. For engineers, grasping the real mechanism behind hoisting helps avoid confusing bugs around undefined values, TDZ errors, and function-expression pitfalls, and supports more informed choices between var, let, and const during code review.

» SourceDev.to