Demystifying Hoisting: What Really Happens Inside the JavaScript Engine

Most JavaScript developers have heard the common statement: "JavaScript moves variables and functions to the top of your file." While this explanation is widespread, it is technically incorrect. Hoisting is not code movement. Nothing is physically shifted around in your source file. Instead, hoisting is the direct result of how the JavaScript engine prepares memory before executing a single line of your code.

Once you understand what happens internally during this preparation step, hoisting becomes one of the easiest JavaScript concepts to grasp.

Why Hoisting Exists: The Two-Pass Model

JavaScript does not just execute your code immediately, line by line. Before execution starts, the JavaScript engine performs a crucial preparation step where it scans your code, identifies variables and functions, and allocates memory for them.