// Code A:console.log(message); // ???var message = "Hello! 👋";
// Code B:sayHello(); // ???function sayHello() { console.log("Hello! 👋");}JavaScript Hoisting: Understanding Variables and Functions Before Execution
Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.
What is JavaScript Hoisting? Core Concept & Direct Summary
What is hoisting in JavaScript?
How Does JavaScript Hoisting Work? In-Depth Mechanics & Architecture
Here are two pieces of code. One works. One explodes. Can you guess which is which?
The twist:Code A printsundefined(no error!), while Code B runs perfectly — the function executesbeforeits own definition. 🤯
Both behaviors come from the same JavaScript mechanism:hoisting— the reason JavaScript seems to "know about" variables and functions before it reaches their lines. It's one of the most-asked interview topics in all of JavaScript, and one of the most misunderstood.
In this lesson, you'll learn what hoistingactuallyis (it's not what most tutorials say!), howvar,let,const, and functions each behave differently, and the mysterioustemporal dead zonethat's been name-dropped sinceLesson 4. Let's lift the curtain. 🎩
What Is Hoisting? (The Truth, Not the Myth) 🎈
The popular myth:"JavaScript physically moves declarations to the top of your file." ❌ Not true — your code never moves.
What actually happens:JavaScript runs your code intwo phases:
Phase 1: The Creation Phase 📋
Before executing a single line, JavaScript scans the entire scope andregisters all declarations— setting aside memory for every variable and function:
vardeclarations → registered AND initialized toundefinedlet/constdeclarations → registered but leftuninitialized💀- Function declarations → registeredcompletely(name + entire body!)
Phase 2: The Execution Phase ▶️
Now your code runs line by line — but the declarations are already in memory. That's why they're "known" before their lines execute.
Hoisting = the creation phase preparing memory before execution begins.Nothing moves; everything ispre-registered.
Hoisting with var: The Ghost Variable 👻
Whyundefinedand not an error?During the creation phase,var messagewas registered and initialized toundefined. So at execution time, the variableexists— it just holds the placeholderundefined.
How JavaScript effectively treats it:
⚠️Key insight:only thedeclarationis hoisted — theassignment stays put.This is the #1 hoisting misunderstanding in interviews.
Hoisting with let & const: The Temporal Dead Zone 💀
Now watch the same code withlet:
An error! But wait — didn't we say all declarations are hoisted? Yes! Andletishoisted… but with a twist:
let and const are hoisted but left UNINITIALIZED.The variable exists in memory, but JavaScript forbids touching it until the declaration line executes.
That forbidden window — from the start of the scope until the declaration line — is theTemporal Dead Zone (TDZ):
The Complete Comparison 🏆 (Interview Gold)
Which behavior is safer?The TDZ error, by far.var's silentundefinedlets bugs slip through;let/constscream immediately. This is yet another reason (with Lessons 4 and 10) that modern JavaScript abandonedvar— and a favorite interview follow-up:"Is let hoisted?"Yes — but the TDZ protects you from it.
🕳️ The Sneaky TDZ Trap
Watch this confusing classic:
You'd expect the global to print… but thelocallet brandis hoisted within the function, putting the whole function in its TDZ — shadowing the global (Lesson 10's shadowing!)beforeit even initializes. The function's own declaration blocks access to everything namedbrandabove the line.
Function Hoisting: The Full Ride 🎢
Function Declarations — FULLY Hoisted ✅
Function declarations are hoistedcompletely— nameandbody. The entire function is ready before execution begins. This is why helper functions can live at the bottom of a file while the main logic at the top calls them. Many developers use this deliberately:"main logic up top, helpers below."
Function Expressions — NOT Callable Early ❌
FromLesson 39:
Theconst greetvariable is hoisted into the TDZ — but the function value doesn't exist until the assignment line. Calling early hits the dead zone.
Arrow Functions — Same Rule ❌
And with var? The Halfway Trap 😬
Why TypeError, not ReferenceError?var greetwas hoistedandinitialized toundefined— so you're callingundefined()→ "not a function." Different keyword, different error, same broken result.
The Function Hoisting Summary 🃏
🎤 The Interview Hall of Fame
Test yourself against the classics:
If you can explain Q5'sundefined—local declaration hoisted, assignment in place, global shadowed— you understand hoisting better than most working developers. 🎓
Best Practices: Working WITH Hoisting 🏆
Hoisting isn't a bug to fight — it's a mechanism to respect:
- Declare before you use—
let/constat the top of their scope. The TDZ then protects you automatically. - Use let/const, never var— Lesson 4's rule; hoisting weirdness is a big reason why.
- Define expressions before calling them— treat
const fn = …like a variable (because it is one!). - Function declarations anywhere— hoisting makes them location-flexible; many devs put main logic first, helpers below. That's a style choice hoisting makes safe.
- When you see
undefinedunexpectedly— your first thought should now be:"Did something get used before its assignment?"🕵️
🛠️ See the Two Phases Live (Test Lab)
Output:
Three different hoisting behaviors, one scope, live proof. Run it yourself! 🔬
Common Beginner Mistakes (And Fixes)
Quick Self-Check: Lesson 40 Quiz 🧠
- In one sentence: what is hoisting in JavaScript?
- What's the output?
- What's the output?
- Why does a functiondeclarationwork before its line, but a functionexpressiondoesn't?
- What's the output — and why?
(Answers: 1. JavaScript's creation phase registers declarations in memory before executing code — var initialized to undefined, let/const uninitialized (TDZ), function declarations fully · 2. undefined — the declaration hoisted, the assignment stayed · 3. ReferenceError — b is in the temporal dead zone · 4. Declarations hoist completely (name + body); expressions are variables whose function value isn't assigned until the line runs · 5. undefined — the local var n hoists within f(), shadowing the global; the console.log runs before the local assignment)
JavaScript Decision Matrix & Syntax Comparison
Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.
var vs let vs const| Feature / Property | var (Legacy ES5) | let (Modern ES6+) | const (Modern ES6+) |
|---|---|---|---|
| Scope | Function Scope | Block Scope ({}) | Block Scope ({}) |
| Hoisting Behavior | Hoisted (initialized as undefined) | Hoisted (Temporal Dead Zone - ReferenceError) | Hoisted (Temporal Dead Zone - ReferenceError) |
| Reassignable | ✓ Yes | ✓ Yes | ✗ No (Immutable binding) |
| Redeclarable in Same Scope | ✓ Yes (Error-prone) | ✗ No (SyntaxError) | ✗ No (SyntaxError) |
| Window Object Binding | Creates property on window | Does not attach to window | Does not attach to window |
| Dimension | Client-Side (Web Browser) | Server-Side (Node.js / Deno) |
|---|---|---|
| Global Object | window, document, navigator | global, process, globalThis |
| DOM & UI Manipulation | ✓ Full access (document.querySelector) | ✗ No DOM (Headless / Non-UI) |
| File System & OS Access | ✗ Blocked (Sandboxed security) | ✓ Full access (fs, os, child_process) |
| Primary Focus | Interactive UI, animations, client state | REST APIs, microservices, databases, I/O streaming |
Runnable JavaScript Code Example & Practical Implementation
console.log(myVar);
// undefined (var hoisted)
var myVar = 'Hello';
sayHi();
// Works! Function definition hoisted
function sayHi() {
console.log('Hi!');
}Frequently Asked Questions & Technical Interview Insights
Technical Interview & Viva Questions
Frequently asked questions for frontend & full-stack rolesQ: What gets hoisted first: function declarations or variable declarations?
Related Tools, Tutorials & Authoritative References
Recommended Interactive Tools
- Online JavaScript Editor & IDE — Browser-based JavaScript workspace with live console and DOM inspector.
- C Programming Tutorial — Master memory allocation, pointers, and systems programming fundamentals.
- C++ Programming Tutorial — Explore Object-Oriented Programming, templates, and high-performance STL.
- Online Code Editors & Compilers — Complete development tool suite for 20+ programming languages.
Authoritative Standards & Citations
- ECMA-262 ECMAScript Language Specification — The official international JavaScript language specification maintained by TC39.
- MDN Web Docs (Mozilla Developer Network) — Authoritative documentation and API guide for JavaScript and Web APIs.
- Google V8 JavaScript Engine — Open-source high-performance JavaScript and WebAssembly engine documentation.
- Node.js Official Documentation — Server-side JavaScript runtime API specification and reference.