Skip to content
Lydia Hallie theavocoder
Course contents
Complete JavaScript / Lesson 17

Call stack

You can visualize the call stack as a pile of books. Each book represents a function that’s invoked in our code. The “book” that’s on top is the function that’s currently running. We start “piling those books” after our code has been loaded to the webpage.

Let’s say we have the following code:

Call stack diagram 1

Whenever this code gets loaded on a webpage, the first function that’s being added to the call stack is the Global Execution Context.

Call stack diagram

Then, we invoke the multiply function. This get added to the stack.

Call stack diagram

Then, when the function returns, it gets popped off the stack.

Call stack diagram

Then, the add function gets called, and the same steps are taken for this function. Once the add function gets invoked, it gets added to the stack, and popped off once it returned a value.

Now, imagine that a function calls another function. That means that the function doesn’t yet return, so it doesn’t get popped off the stack, and it invokes another function. This function then gets added to the top of the stack, and only pops off once that function returns. Example:

Call stack diagram 5

After the function has been invoked, the call stack would look like:

Call stack diagram 6Call stack diagram 7Call stack diagram 8Call stack diagram 9
Call stack diagram 10

References and further reading