DEV Community

Cover image for Understanding Execution Context & the Call Stack – JavaScript Deep Dive
Chaitanya Chopde
Chaitanya Chopde

Posted on

Understanding Execution Context & the Call Stack – JavaScript Deep Dive

πŸš€ Introduction

Have you ever wondered what really happens when your JavaScript code runs?

When you write a function and call it β€” how does JavaScript know what to execute, in what order, and where to return after a function ends?

The answer lies in two core concepts:

βœ… Execution Context

βœ… Call Stack

Let’s break them down with visual examples and relatable metaphors.

πŸ” What is Execution Context?

An execution context is an environment where JavaScript code is evaluated and executed.

There are three main types:

  1. Global Execution Context (GEC)
  • Created by default when your script starts.
  • this refers to the window object in browsers.
  1. Function Execution Context (FEC)
  • Created whenever a function is called.
  • Has its own this, arguments, variables, and scope.

3.Eval Execution Context (rarely used)

  • Created inside the eval() function (avoid using this in practice).

🧱 Inside an Execution Context
Each execution context has two phases:

  • Creation Phase
  • Sets up memory space for variables and functions.
  • var is hoisted with undefined, functions are hoisted completely.
  • Execution Phase
  • Code is executed line by line.

🧰 Example:

Image description

  • Global Execution Context is created.
  • Function greet() is hoisted.
  • Then greet() is invoked, creating a new Function Execution Context.
  • It runs, logs the output, and is removed from memory.

🧡 What is the Call Stack?

  • The Call Stack is like a stack of plates.
  • When a function is called, it’s pushed onto the stack.
  • When it finishes, it’s popped off.
  • This stack helps JavaScript keep track of where it is in the program β€” especially when there are multiple nested function calls.

πŸ§ͺ Call Stack Example

Image description

⚠️ Call Stack Overflow

Image description

πŸ§‘β€πŸ« Summary

  • JavaScript runs inside Execution Contexts.
  • The Call Stack keeps track of function calls.
  • Understanding this is key to debugging and mastering asynchronous code (coming in Day 3!)

βœ… Conclusion

Understanding the Execution Context and the Call Stack is like knowing the brain of JavaScript. It tells you:

  • Where your code is executed
  • How functions are managed
  • Why errors like β€œstack overflow” happen
  • And how JavaScript handles synchronous flow

✍️ Written By
Chaitanya Chopde

🌟 Inspired By
@devsyncin

Top comments (0)