⚡ What Is Hoisting in JavaScript?
⚡ What Is Hoisting in JavaScript?
Hoisting means that JavaScript moves variable and function declarations to the top of their scope (before code execution) — but not the initialization.
So JavaScript “knows” about your variables and functions before it runs your code, but values are not yet assigned.
๐ง  Example 1 — Variable Hoisting (with var)
console.log(a); // ๐ undefined
var a = 10;
๐ Behind the Scenes
JavaScript internally does this:
var a;       // Declaration is hoisted
console.log(a);
a = 10;      // Initialization stays in place
✅ So it doesn’t throw an error — it just logs undefined.
๐ซ let and const Are Not Fully Hoisted
console.log(b); // ❌ ReferenceError: Cannot access 'b' before initialization
let b = 20;
✅ Explanation:
- 
letandconstare hoisted, but they are not initialized until the execution reaches that line.
- 
The time between hoisting and initialization is called the Temporal Dead Zone (TDZ). 
๐งฉ Example 2 — Function Hoisting
sayHello(); // ✅ Works fine
function sayHello() {
  console.log("Hello!");
}
✅ Output:
Hello!
Why?
Because function declarations are fully hoisted — both their name and definition.
⚠️ Example 3 — Function Expression (Not Hoisted)
sayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function() {
  console.log("Hi!");
};
What Happens:
var sayHi; // declaration hoisted
sayHi();   // sayHi is undefined here
sayHi = function() {...}
So it throws a TypeError, not a ReferenceError.
✅ Summary Table
| Type | Hoisted? | Initialized? | Usable Before Declaration? | Notes | 
|---|---|---|---|---|
| var | ✅ Yes | ❌ No | ⚠️ Yes, but undefined | Function-scoped | 
| let | ✅ Yes | ❌ No | ❌ No (TDZ error) | Block-scoped | 
| const | ✅ Yes | ❌ No | ❌ No (TDZ error) | Block-scoped | 
| Function Declaration | ✅ Yes | ✅ Yes | ✅ Yes | Fully hoisted | 
| Function Expression | ✅ Yes (name only) | ❌ No | ❌ No | Acts like var | 
๐ก In Short
๐งฉ Hoisting = JavaScript’s way of processing declarations before executing code.
It means “you can use a function or variable before it appears in the code,” depending on how it’s declared.
Would you like me to show a visual memory diagram of how the JavaScript engine treats variables during hoisting (execution context + TDZ)?
Comments
Post a Comment