Hello! Welcome back.
In our last lesson, we introduced the idea of an Execution Context—the environment where your code runs. We learned that a new execution context is created every time a function is called, which explains why variables inside a function are private to it. This naturally leads to a question: if you call a function, which then calls another function, how does JavaScript keep track of all these active contexts?
Today, we'll answer that by visualizing how JavaScript manages this process using a mechanism called the Call Stack. The call stack is the engine's internal "to-do list" for functions. Understanding it is a huge step toward thinking like the JavaScript engine, which is invaluable for debugging complex code and grasping asynchronous programming later on.
By the end of this lesson, you will be able to visualize how the call stack tracks function execution.
The Call Stack: JavaScript's To-Do List
Because JavaScript is single-threaded, it can only do one thing at a time. The call stack is the data structure it uses to manage the order of function calls.
Imagine you're washing a stack of plates. You add a dirty plate to the top of the stack. When you're ready to wash, you take a plate from the top, wash it, and put it aside. You never pull a plate from the middle or the bottom.
This principle is called LIFO: Last-In, First-Out. The last plate you added is the first one you take off. The call stack works exactly the same way with function calls.
- "In" (Push): When you call a function, JavaScript creates an execution context for it and pushes it onto the top of the stack.
- "Out" (Pop): When the function finishes (i.e., it hits a
returnstatement or the end of its code), its execution context is popped off the top of the stack.
Call Stack - 33 JavaScript Concepts
The article 'Call Stack' from 33 JavaScript Concepts provides a great introduction using this very analogy.
Please read the first two short sections, 'The Stack of Plates: A Real-World Analogy' and 'What is the Call Stack?'. Focus on the LIFO principle and how it relates to function calls.
Visualizing the Call Stack in Action
Let's trace a simple example to see the call stack work.
function one() {
console.log('Running one...');
two();
console.log('...one is done.');
}
function two() {
console.log('Running two...');
three();
console.log('...two is done.');
}
function three() {
console.log('Running three...');
}
// Start of the program
console.log('Program starting...');
one();
console.log('...program finished.');
Here is a visual breakdown of what happens in the call stack as this code runs:

Let's walk through the process:
- Program Starts: The script begins. A base global execution context is created and pushed onto the stack. Think of this as the main "anonymous" function that runs your entire file.
one()is called: Theone()function is invoked. A new execution context foroneis created and pushed onto the top of the stack. The stack now looks like:[one, global].two()is called: Insideone(), thetwo()function is invoked. A new context fortwois pushed on top. The stack is now:[two, one, global].three()is called: Insidetwo(),three()is invoked. Its context is pushed on top. The stack is at its deepest:[three, two, one, global].three()finishes: Thethree()function runs itsconsole.logand then finishes. Its context is popped off the stack. The stack is now:[two, one, global].two()finishes: Control returns totwo(). It runs its finalconsole.logand finishes. Its context is popped off. The stack is now:[one, global].one()finishes: Control returns toone(). It runs its finalconsole.logand finishes. Its context is popped off. The stack is now just:[global].- Program Finishes: The script has no more code to run. The global context is popped off, and the stack is empty.
A Deeper Look: The Call Stack and Execution Contexts
You've requested a deep dive into the theory, and this is where everything connects. The "items" being pushed and popped from the call stack are the very Execution Contexts we discussed in the last lesson. Each entry on the stack is also known as a stack frame.
This next video provides a fantastic, animated visualization that ties these concepts together. It's a bit more technical, but it perfectly illustrates what's happening "under the hood."
JavaScript Visualized - Execution Contexts
The video 'JavaScript Visualized - Execution Contexts' by Lydia Hallie animates the entire lifecycle of execution contexts and their relationship with the call stack. Watching this will solidify your mental model of how JavaScript executes code.
Please watch from 06:15 to 08:57. This is the core of our lesson. As you watch, focus on these key moments: (06:15) The Global Execution Context is pushed onto the call stack. (06:46) The greet() function is called, and a new Function Execution Context is created. (07:55) This new function context is pushed onto the top of the call stack. (08:33) The greet() function returns, and its context is popped off the call stack. (08:50) The script finishes, and the Global Execution Context is popped off.
This animation makes it clear: the call stack is not just a list of function names; it's a stack of active execution environments, each with its own memory for variables and a plan for what to do.
The Call Stack in Practice: Debugging
So, why is this important for your goal of learning Next.js and TypeScript? Because when your code breaks, the call stack is your best friend. The browser's debugger shows you the state of the call stack at the exact moment an error occurs or when you pause the code.
Using the Debugger
Let's see how to observe the call stack in a real browser.
The JS Call Stack Explained In 9 Minutes
In 'The JS Call Stack Explained In 9 Minutes', Colt Steele provides a clear, practical demonstration of using the Chrome debugger to watch the call stack live.
Please watch from 05:13 to 07:24. In this segment, he sets a breakpoint in his code, which pauses execution. You can then see the 'Call Stack' panel in the debugger, showing exactly which functions are currently active and in what order. This is the most direct way to visualize the call stack.
Stack Overflow: When the Stack Gets Too Big
The call stack has a limited size. If you keep pushing functions onto it without ever popping them off, you will eventually run out of memory. This triggers a famous error: "Maximum call stack size exceeded." This is known as a stack overflow.
The most common cause is a recursive function that never reaches its exit condition—it just calls itself forever.
// ⚠️ This code will crash your browser tab!
function goForever() {
goForever(); // Calls itself with no way to stop.
}
goForever();
Each call to goForever() pushes a new frame onto the stack. Since it never returns, nothing is ever popped off. The stack grows until it hits the browser's limit and crashes.
Test your understanding!
Without running the code, trace the call stack. What will the call stack look like right after calculateAverage() is called but before it returns? List the functions on the stack from top to bottom.
function calculateAverage(a, b) {
const sum = add(a, b);
return sum / 2;
}
function add(x, y) {
return x + y;
}
function runCalculation() {
const avg = calculateAverage(10, 20);
console.log(`The average is: ${avg}`);
}
runCalculation();
Show answer
At that point in the execution, the call stack would look like this (from top to bottom):
add(It was just called bycalculateAverage)calculateAverage(It calledaddand is waiting for it to return)runCalculation(It calledcalculateAverageand is waiting)anonymous/global(The main script context)
The stack is [add, calculateAverage, runCalculation, anonymous].
Conclusion
Great job! You've just visualized one of the most fundamental mechanisms in the JavaScript engine. This mental model will be incredibly helpful as we move into more complex topics.
Key Takeaways:
- The Call Stack manages the order of function calls in JavaScript's single-threaded environment.
- It follows a LIFO (Last-In, First-Out) principle: the last function called is the first to finish.
- Each item on the stack is an Execution Context (or "stack frame").
- When a function is called, its context is pushed onto the stack. When it returns, its context is popped off.
- A stack overflow error occurs when the call stack exceeds its maximum size, usually due to infinite recursion.
- You can use browser debuggers to inspect the call stack, which is a powerful tool for finding bugs.
Next Up:
We've seen that an execution context has two phases: creation and execution. In the next lesson, we'll focus on that creation phase to understand a peculiar but important JavaScript behavior: hoisting. We'll see why you can sometimes use functions and variables before they appear to be declared in your code.