DEV Community

Cover image for Call Stack - A simplified intro
Kani Gureye
Kani Gureye

Posted on

Call Stack - A simplified intro

What is it?

The call stack is a data structure that records the execution of functions in JavaScript. Whenever a function is called, it is added to the top of the call stack, and when a function completes its execution, it is removed from the stack. The call stack follows a last-in, first-out (LIFO) principle, meaning that the last function added to the stack is the first function to be executed.

In order to better manage this, the JS engine uses the call stack to handle execution contexts. They are the following:

Main ones

  • Global execution context - for code that’s in the global context
  • Function execution contexts - for code that’s inside a function

Occasionally

  • Eval execution context - for when we use the eval method (creates its own execution context)

When you execute a script, the JavaScript engine creates a global execution context and pushes it on top of the call stack.

Whenever a function is called, the JavaScript engine creates a function execution context for the function, pushes it on top of the call stack, and starts executing the function.

If a function calls another function, the JavaScript engine creates a new function execution context for the function being called and pushes it on top of the call stack.

When the current function completes, the JavaScript engine pops it off of the call stack and resumes the execution where it left off.The script will stop when the call stack is empty.

In order to better understand this, consider the following example code:


function one() {
  console.log('one');
}

function two() {
  console.log('two');
  one();
}

function three() {
  console.log('three');
  two();
}

three();
Enter fullscreen mode Exit fullscreen mode

In this example, the three function is called, which then calls the two function, which in turn calls the one function. The call stack will record the execution of these functions in the following order:

1. three
2. two
3. one

Enter fullscreen mode Exit fullscreen mode

Stack empties in following order:

1. one
2. two
3. three

Enter fullscreen mode Exit fullscreen mode

When the one function completes its execution, it is removed from the stack, and the same goes for the two function. Finally, when the three function completes its execution, it is removed from the stack, and the stack becomes empty again.

Summary

  • The JS engine uses a call stack to manage execution contexts.
  • The call stack uses the stack data structure that works based on the LIFO (last-in-first-out) principle. It's similar to array and uses methods pop and push.
  • Only one function is removed at a time because JS is single-threaded. It can only handle one task at a time.

Where can we learn more?

Philip Roberts - JSConf EU
Chrome DevTools

Thanks for reading and I would love to connect on Twitter!

Top comments (0)