DEV Community

Hargunbeer Singh
Hargunbeer Singh

Posted on

What is call stack?


Call stack is a mechanism for the interpreter to keep track of its place in a script that executes multiple functions inside of other functions. It keeps track of what functions are being run, and what function have been paused.

How does a call stack work

Suppose you have a function called getToy inside of another function called play:

// script.js
function play(){
    console.log("playing started");
    console.log("playing ended");
function getToy(){
    console.log("Got the toy");
console.log("script ended");
Enter fullscreen mode Exit fullscreen mode

The call stack mechanism would be used here. The call stack would execute the functions in this order:

  1. The interpreter does not read the declaration of the functions and straight away reads play(), then it reads the declaration of the function and adds it to the call stack.
  2. Execute the first line of code in the play function, which would print playing started to the console.
  3. Read the invocation of the getToy function, then it reads the declaration of the getToy function and adds it to the call stack
  4. Pauses the play function's execution from the call stack
  5. Runs the getToy function, which would print Got the toy to the console.
  6. Resumes the play function's execution from the call stack and executes the code from the point where the call stack was paused.
  7. After the play function is done executing, the call stack removes the play function from the call stack list
  8. The interpreter goes on to execute the other JS script code, i.e. the last line which would print script ended to the console

Stack Overflow* Error

When a function takes up more memory than the memory assigned to it in the call stack, it returns a stack overflow error. This is due to a lot of other functions being executed in a particular function.

*Not to be confused with the StackOverFlow platform

Top comments (0)