JavaScript Hoisting
Hoisting is JavaScript’s behavior of moving declarations to the top of their scope during the compilation phase, before the code runs.
However, initializations are not hoisted, and the behavior differs for var
, let
, const
, and functions.
How Hoisting Works
- Only declarations are hoisted — not initializations.
var
variables are hoisted and initialized asundefined
.let
andconst
are hoisted but not initialized — they stay in the Temporal Dead Zone (TDZ) until their declaration line.- Function declarations are fully hoisted (both name and body).
- Function expressions are not hoisted.
Example 1: var
Hoisting
var x
is hoisted to the top, but its value (5
) is assigned later.
console.log(x); // undefined (hoisted, but not initialized)
var x = 5;
console.log(x); // 5
It’s as if the code runs like this:
var x;
console.log(x); // undefined
x = 5;
console.log(x); // 5
Example 2: let
/ const
Hoisting (Temporal Dead Zone)
let
and const
are hoisted but remain uninitialized in the Temporal Dead Zone (TDZ) — accessing them before declaration throws an error.
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(y); // 10
Example 3: Function Declaration Hoisting
Function declarations are fully hoisted — you can call them before their definition.
myFunc(); // Works: "Hello!"
function myFunc() {
console.log("Hello!");
}
Example 4: Function Expression (Not Hoisted)
Here, only the var
declaration is hoisted (as undefined
), not the assigned function.
That’s why calling it before definition causes an error.
// myFunc(); // Error: myFunc is not a function
var myFunc = function() {
console.log("Not hoisted!");
};
myFunc(); // "Not hoisted!"