Understanding JavaScript Execution Context for Predictable Code

Part 1 - Execution Context: The Mental Model Behind Hoisting 📌 Frontend Interview Series - Execution Context Hoisting isn’t confusing. What’s confusing is skipping execution context. Once you understand this, JavaScript stops feeling unpredictable. Most explanations say: “Execution context is the environment where code runs.” That sounds right — but it doesn’t help you answer: - Why variables exist before execution - Why this changes - Why each function feels isolated So here’s the model interviewers actually expect you to reason with. Mental Model: An execution context is a runtime container JavaScript creates to run code. Each container holds: - Variables - Functions - Scope chain - 'this' binding JavaScript creates this container in two phases: 1️⃣ Memory Creation Phase (before execution) - var → allocated + initialized as undefined - Function declarations → stored with full body - let / const → allocated but uninitialized (TDZ) - this is set This phase explains hoisting. No code moves. Memory is prepared. 2️⃣ Execution Phase - Code runs line by line - Values are assigned - Functions are executed Every time a function is called, JavaScript creates a new execution context - a fresh container with its own memory. Key Insight Execution context answers when memory exists, not where code is written. That’s why: - Hoisting behaves the way it does - Variables don’t collide - this isn’t random - Function calls don’t interfere with each other - Nested calls behave predictably Next If JavaScript keeps creating execution contexts… how does it decide which one runs first? That decision is handled by the call stack. #JavaScript #FrontendEngineering #ExecutionContext #LearningInPublic #WebDev #InterviewThinking

To view or add a comment, sign in

Explore content categories