What is call stack?
Hargunbeer Singh
Posted on August 15, 2021
Introduction
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");
getToy();
console.log("playing ended");
}
function getToy(){
console.log("Got the toy");
}
play()
console.log("script ended");
The call stack mechanism would be used here. The call stack would execute the functions in this order:
- 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. - Execute the first line of code in the play function, which would print
playing started
to the console. - Read the invocation of the
getToy
function, then it reads the declaration of the getToy function and adds it to the call stack - Pauses the play function's execution from the call stack
- Runs the getToy function, which would print
Got the toy
to the console. - Resumes the play function's execution from the call stack and executes the code from the point where the call stack was paused.
- After the play function is done executing, the call stack removes the play function from the call stack list
- 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
Posted on August 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.