✅ Answer (Explained in Points)
🔹 1. What is Hoisting?
- Hoisting is JavaScript’s behavior of moving declarations to the top of their scope (global or function) during the creation phase of execution context.
- Only declarations are hoisted, not initializations.
🔹 2. What Gets Hoisted?
- Variable Declarations with
var- The declaration is hoisted, but initialized with
undefined.
- The declaration is hoisted, but initialized with
console.log(a); // undefined var a = 10;
Function Declarations
- The entire function body is hoisted.
greet(); // "Hello"
function greet() { console.log("Hello"); }
Class Declarations (partially hoisted)
- Class declarations are hoisted but put in a temporal dead zone (TDZ) until defined.
const obj = new MyClass(); // ReferenceError
class MyClass {}
3. What Does Not Get Hoisted (or Works Differently)?
letandconstvariables- Declared but not initialized → live in the temporal dead zone until the actual line of declaration.
console.log(x); // ReferenceError let x = 5;
Function Expressions & Arrow Functions
- If assigned with
var→ variable is hoisted asundefined, not the function body.
sayHi(); // TypeError: sayHi is not a function
var sayHi = () => console.log("Hi");
Class Expressions
- Same behavior as
let/const, not accessible before declaration.
🔹 4. Key Differences to Remember
var→ hoisted, initialized withundefined.let&const→ hoisted, but not initialized (TDZ).- Function Declaration → fully hoisted with body.
- Function Expression / Arrow Function → variable hoisted, function not.
- Class Declaration → hoisted but in TDZ, not usable before definition.
🔹 5. Interview-Friendly Summary
- Hoisting = Declarations go up, initializations stay down.
- Safe rule: Always declare variables and functions before using them.