π 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:
- Global Execution Context (GEC)
- Created by default when your script starts.
- this refers to the window object in browsers.
- 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:
- 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
β οΈ Call Stack Overflow
π§βπ« 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)