How to understand hoisting in JavaScript
· Category: JavaScript
Short answer
Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution, but only var and function declarations are initialized with undefined; let and const enter a temporal dead zone.
Steps
vardeclarations are hoisted and initialized asundefined:javascript console.log(a); // undefined var a = 5;letandconstare hoisted but not initialized:javascript console.log(b); // ReferenceError let b = 5;- Function declarations are fully hoisted:
javascript sayHi(); // works function sayHi() { console.log('Hi'); } - Function expressions are not hoisted:
javascript sayBye(); // TypeError var sayBye = function() { console.log('Bye'); };
Tips
- Declare variables at the top of their scope to avoid surprises.
- Prefer
letandconstbecause the temporal dead zone catches errors early.
Common issues
- Repeating
varinside loops with closures captures the same hoisted variable. - Calling a function expression before its assignment throws an error.