Hoisting is a JavaScript behavior where variable and function declarations are processed before code execution begins.
The behavior of hoisting depends on how the variable is declared.
Variables declared with var are hoisted and initialized with undefined.
console.log(a); // undefined
var a = 10;Variables declared with let and const are hoisted but not initialized. Accessing them before declaration results in an error due to the Temporal Dead Zone (TDZ).
console.log(b); // ReferenceError
let b = 20;Note: The Temporal Dead Zone is the time between entering a scope and declaring the variable, during which the variable cannot be accessed.
Function declarations are fully hoisted, meaning they can be called before they are defined.
greet();
function greet() {
console.log("Hola!");
}Function expressions are not hoisted the same way. If assigned to var, only the variable is hoisted.
sayHi(); // TypeError
var sayHi = function () {
console.log("Hi");
};- Accessing variables before declaration can cause unexpected bugs
varhoisting can silently returnundefinedletandconstcan throw ReferenceError due to TDZ- Function expressions may cause TypeError if called early
- Always declare variables at the top of their scope
- Prefer
letandconstovervar - Avoid using variables before they are declared
- Use function declarations when hoisting behavior is required
Note: Understanding hoisting helps you write predictable code and avoid runtime errors, especially when working with larger codebases.