Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their containing scope during the compilation phase before code execution.
flowchart TD
Phase1["1. Compilation Phase"] --> FindDecl["Scan & Allocate Memory for Declarations"]
FindDecl --> FuncHoist["Function Declarations: Fully Hoisted & Defined"]
FindDecl --> VarHoist["var Declarations: Hoisted & Initialized to undefined"]
FindDecl --> LetConstHoist["let / const Declarations: Hoisted & Left Uninitialized (TDZ)"]
Phase1 --> Phase2["2. Execution Phase"]
Phase2 --> ExecCode["Execute statements line-by-line"]
| Declaration Type | Hoisted to Scope Top? | Initialized Value During Hoisting | Accessible Before Line? |
|---|---|---|---|
| Function Declaration | Yes | Fully defined callable function | Yes (Can invoke before line) |
var Variable |
Yes | undefined |
Yes (Returns undefined) |
let / const Variable |
Yes | Uninitialized (TDZ) | No (Throws ReferenceError) |
| Function Expression | Follows variable rules | Follows var / let / const rule |
No |
// Demonstrating Hoisting of Function Declarations vs var vs let/const
// 1. Function Declaration Hoisting (Callable before line)
console.log(`Hoisted Function Result: ${sum(10, 20)}`); // Works!
function sum(a, b) {
return a + b;
}
// 2. var Hoisting (Returns undefined before line)
console.log(`var before declaration: ${hoistedVar}`); // undefined
var hoistedVar = "I am var";
// 3. Function Expression Hoisting Failure
try {
// hoistedExpression(); // Throws TypeError: hoistedExpression is not a function
} catch (e) {
console.error(`Expression Hoisting Error: ${e.message}`);
}
var hoistedExpression = function() {
console.log("Function expression");
};
// 4. let / const Temporal Dead Zone (TDZ)
try {
// console.log(letVar); // Throws ReferenceError: Cannot access 'letVar' before initialization
let letVar = "I am let";
} catch (e) {
console.error(`TDZ Access Error: ${e.message}`);
}
var: Never rely on var hoisting returning undefined.What is printed to the console when console.log(x); var x = 100; is executed vs console.log(x); let x = 100;?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.