📦 JavaScript Hoisting — What Runs First?


✍️ Written by Chaitanya Chopde
🎨 Inspired by Devsync —
🧠 What Is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (script or function).
That means:
You can use variables and functions before you declare them — but with caveats.
🧪 Variable Hoisting (with var
)
jsCopyEditconsole.log(name); // undefined
var name = "Hasnide";
✅ JavaScript hoisted the declaration (var name
), but not the value ("Hasnide"
), so it prints undefined
.
❌ Let & Const Are Not Hoisted the Same Way
jsCopyEditconsole.log(age); // ❌ ReferenceError
let age = 25;
With let
and const
, the variable is hoisted but placed in a temporal dead zone (TDZ) — you can’t access it before declaration.
🧱 Function Hoisting
✅ Function Declarations Are Fully Hoisted
jsCopyEditgreet(); // Hello!
function greet() {
console.log("Hello!");
}
✅ Safe to use before the definition.
❌ Function Expressions Are NOT Hoisted
jsCopyEditsayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function () {
console.log("Hi!");
};
Only the variable sayHi
is hoisted, not the function. It’s undefined
at the time of the call.
🧠 Extra Theory: Why Hoisting Exists
JavaScript compiles code before execution. During this phase:
All declarations (
var
,function
) are scannedThey're hoisted to the top of their scope
Assignments and logic are left where they are
Understanding hoisting:
Helps debug weird errors
Explains undefined variables
Is essential for mastering scope and closures
🧪 Real Case: Avoid Bugs
jsCopyEditfunction run() {
if (!flag) {
var flag = true;
console.log("Flag is false at start"); // runs
}
}
run();
Even though flag
is defined later, it's hoisted to the top of the function with undefined
, making the if (!flag)
condition true
.
✅ Best Practices
Always declare variables at the top of their scope
Prefer
let
andconst
overvar
Know the difference between function declarations and function expressions
🧠 Interview Insight
“Explain hoisting in JavaScript” is a top interview question.
Knowing what gets hoisted and what doesn’t sets you apart from surface-level coders.
✅ Conclusion
JavaScript Hoisting is a quirky but crucial part of how the language runs your code.
For Hasnide and anyone learning JS seriously — understanding hoisting means understanding flow.
Master hoisting and you’ll write cleaner, more predictable JavaScript — and crush those confusing bugs before they bite. 🧯
✍️ Written by:
Chaitanya Chopde
🎨 Blog Inspired by Devsync — Teaching the "Why", not just the "How"
📫 chaitanyachopde14@gmail.com
Subscribe to my newsletter
Read articles from Chaitanya Chopde directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Chaitanya Chopde
Chaitanya Chopde
Hey, I'm Chaitanya Chopde 💻 Web Development Learner | Frontend Focused 🛠️ Learning HTML, CSS, JavaScript & Figma ✍️ Writing to share my dev journey, tips & projects 🏷️ #DevsyncLearning | Building one line of code at a time