Inside JavaScript's Precompilation: The Hidden Step That Decides Variable Values
This breakdown turns JavaScript's hoisting quirk into a predictable sequence of declaration registration and assignment. For developers debugging why a local variable shadows a global one or why a function declaration overrides a variable declaration, the exact order of precompilation steps removes the guesswork.
Before a single statement runs, the JavaScript engine precompiles the current scope. This phase registers variable declarations as undefined, binds function declarations to their bodies, and (in function scopes) links parameters to arguments. The result is the execution context: the global object (GO) for the script's top level, and an activation object (AO) for each function call.
The registration order is what separates predictable behavior from confusion. In a function, the engine first sets parameters and variables to undefined, then binds parameters to arguments, and finally writes function declarations. When a variable and a function share a name, the function declaration wins because it is written last. At runtime, assignments overwrite these initial values in statement order, so the same identifier can hold different values at different points in execution.
The call stack complements this by recording call order, arguments, and return values across nested calls. Together, precompilation and the call stack determine the observable behavior of identifier lookups and value changes during execution.
The sequence inside precompilation is the root cause of hoisting: variable declarations become undefined, then function declarations overwrite them, so a same-named function always wins.
The independence of AO and GO properties explains why local shadowing is a matter of context construction, not lexical scope rules.
The separation of declaration and assignment phases means that a variable's value during execution is a combination of precompiled defaults and statement order, which is why the same identifier can be undefined, a function, or a number at different times.