JavaScript Function Call Execution and Call Stack Explained

Day 2: The Secret Life of a Function Call — Global vs. Local Execution Context 🚀 Today, I went deeper into the "Big Box" of JavaScript to understand exactly what happens when we call a function. Using this simple square function as an example, here is the line-by-line magic: 🎭 The Two-Phase Performance Phase 1: Memory Allocation Before a single line of code runs, JavaScript scans everything. n, square2, and square4 are allocated memory and set to undefined. The square function gets its own memory space with the entire function code stored inside. Phase 2: Code Execution Line 1: n is assigned the value 2. Line 6: This is where it gets interesting! A Function Invocation happens. 📦 The "Mini Box": Functional Execution Context When square(n) is called, a New Execution Context is created inside the Global one! Memory Phase: A local variable ans is created (undefined). Code Phase: num becomes 2, ans becomes 4. The Return Statement: This is the exit signal. It returns the value 4 to square2 and destroys the local execution context immediately. 📚 The Call Stack: The Manager of it All How does JS keep track of these nested boxes? The Call Stack. It's a stack (LIFO - Last In, First Out). Bottom of stack: Global Execution Context (GEC). When a function is called, it's pushed onto the stack. When it returns, it's popped off. 💡 Interview Tip: Did you know the Call Stack has many names? It’s also called the Execution Context Stack, Program Stack, Control Stack, Runtime Stack, or Machine Stack. Understanding how the stack grows and shrinks is the key to mastering Recursion and avoiding the dreaded "Stack Overflow"! Drop a "🚀" if you’re also following the Namaste JavaScript series! #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingLogic #FrontendEngineer #CodingCommunity #JSFundamentals

  • text

To view or add a comment, sign in

Explore content categories