Hoisting is JavaScript declaration processing before execution. The practical debug value is mapping symptoms: undefined reads, early callable function declarations, and ReferenceError or TypeError when the wrong construct is used.
Explain 'hoisting' in JavaScript
Big-picture definition
Hoisting is not code movement. It is how the engine prepares scope before running the script, registering declarations first. That under-the-hood setup explains several debug traps: var reads as undefined, function declarations work early, and function expressions or classes fail for different reasons.
Construct | Hoisted behavior |
|---|---|
| Declaration hoisted, value starts as undefined. |
| Declaration hoisted but inaccessible until declaration line (TDZ). |
Function declaration | Fully available before its line. |
Function expression / arrow assigned to variable | Follows variable rules; not callable early in safe way. |
Class declaration | Hoisted but in TDZ like let/const. |
run(); // works
function run() {}
console.log(a); // undefined
var a = 1;
console.log(b); // ReferenceError
let b = 2;
Practical debugging signal
Error/behavior | Likely cause |
|---|---|
Reads as undefined before declaration |
|
ReferenceError before declaration | TDZ with |
TypeError: fn is not a function before declaration | Function expression assigned later; variable exists but callable value not ready. |
Interview tip
Lead with: "Hoisting registers declarations early; the key difference is what is initialized and when." Then show one var + one let example.
Before the show starts, the stage crew places props (declarations). Some props are usable immediately, others are covered until the right scene (execution line).
- Hoisting is declaration setup before execution.
- It affects variables, functions, and classes differently.
- Understanding initialization timing is what prevents subtle bugs.
Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.