Hoisting in JavaScript
Source: Dev.to
Understanding Execution Context
JavaScript does not execute code strictly top‑to‑bottom.
Before any code runs, the engine creates an execution context where it:
- Allocates memory for variables and functions.
- Stores function declarations in memory.
- Sets the initial value of
var‑declared variables toundefined.
This creation phase is where hoisting occurs – declarations are moved to the top of their scope, but the actual code is not moved.
Variable Hoisting (var)
// Example
console.log(x); // → undefined, not a ReferenceError
var x = 10;
- During the creation phase, JavaScript allocates memory for
xand initializes it withundefined. - The variable is scoped to the function, not the block.
Important
This is not an error becausexwas already created during the creation phase; it simply holdsundefineduntil the assignment runs.
Function Hoisting
// Function declaration
printMessage(); // Works because the function is hoisted
function printMessage() {
console.log('Hello, world!');
}
- The entire function definition is stored in memory during the creation phase.
- Therefore, the engine knows what
printMessageis before execution reaches the call.
When execution starts:
- Line 1 –
printMessage()is called (function already known). - Line 2 –
console.log(x);printsundefined. - Line 3 –
x = 10;assigns the value.
Final output
undefined
Hello, world!
Function Expressions and Arrow Functions
// Function expression
const greet = function() {
console.log('Hi');
};
greet(); // Works after the assignment
// Arrow function (behaves like a function expression)
const add = (a, b) => a + b;
- Function expressions (including arrow functions) are not hoisted in the same way as declarations.
- The variable (
greet,add) is hoisted (asundefinedforvaror in the temporal dead zone forlet/const), but the actual function value is assigned only when the code reaches the expression.
Thus, calling a function expression before its definition results in:
ReferenceErrorforlet/const‑declared variables.TypeErrorforvar‑declared variables that are stillundefined.
Key Takeaways
- Hoisting happens during the creation phase of the execution context, not during execution.
vardeclarations are hoisted with an initial value ofundefined.- Function declarations are fully hoisted, making them callable before their definition appears in the source.
- Function expressions and arrow functions are treated like regular variable assignments; only the variable name is hoisted, not the function value.
- Understanding these rules makes JavaScript’s execution model predictable and easier to reason about.