DEV Community

Cover image for JavaScript Call Stack
Ejjraifi Hamza
Ejjraifi Hamza

Posted on • Updated on

JavaScript Call Stack

JavaScript engine uses a call stack to manage execution contexts: the Global Execution Context and Function Execution Contexts.

The call stack works based on the LIFO principle i.e., last-in-first-out.

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 that is being called and pushes it on top of the call stack.

When the current function completes, the JavaScript engine pops it off the call stack and resumes the execution where it left off in the last code listing.

The script will stop when the call stack is empty.

JavaScript call stack

start with this code below

function add(a, b) {
  return a + b;
}

function average(a, b) {
  return add(a, b) / 2;
}

var x = average(10, 20);
Enter fullscreen mode Exit fullscreen mode

JavaScript engine execute the code above, and right after the calling of average() function, he will take the function call and put it inside call stack, since average() function calling add() function, the same thing will happen again, he will take the function call add() and put it inside call stack

The following figure illustrates this

Call Stack

Stack overflow

The call stack has a fixed size, depending on the implementation of the host environment, either the web browser or Node.js.

If the number of the execution contexts exceeds the size of the stack, a stack overflow will occur.

consider this code below

function foo() {
  foo();
}

foo();
Enter fullscreen mode Exit fullscreen mode

when you execute a recursive function that has no exit condition, it will result in a stack overflow error:

The following figure illustrates this

Stack overflow

that's it for call stack, next post will be about event loop

Summary

In this post, you have learned about the JavaScript call stack that helps keep track of the execution contexts or function calls.

Top comments (0)