Hoisting in JavaScript
Subject: JavaScript
Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope during the compilation phase, before code execution begins. This means you can use variables and functions before they are declared in the code, but their behavior depends on how they are declared (var, let, const, or function).
How Does Hoisting Work?
- Function declarations are hoisted with their definitions.
- Variable declarations using var are hoisted, but only the declaration, not the assignment.
- let and const declarations are hoisted but remain in a temporal dead zone (TDZ) until their declaration line.
Example 1: Hoisting with var
Explanation: This behaves as if the code were:
Example 2: Hoisting with let and const
Explanation: Though let and const are hoisted, they are not initialized, so accessing them before their declaration throws a ReferenceError due to the temporal dead zone.
Example 3: Function Hoisting
Explanation:
The entire function declaration is hoisted, so greet() can be called before it is defined.
Example 4: Function Expression (Not Fully Hoisted)
Explanation:
Only the variable speak is hoisted (as undefined), but the function assignment is not hoisted. Calling it before assignment throws a TypeError.
Key Takeaways
- Hoisting moves declarations (not initializations) to the top of their scope.
- Variables declared with var are hoisted and initialized with
undefined. - Variables declared with let and const are hoisted but reside in the temporal dead zone until initialized.
- Function declarations are fully hoisted.
- Function expressions are not hoisted completely.
- Avoid relying on hoisting; declare variables before using them for clarity and better code maintenance.