What is Callstack ?🤔

Baisali Pradhan
2 min readMar 13, 2022

The call stack is primarily used for function invocation (call). At the most basic level, a call stack is a data structure that uses the Last In, First Out (LIFO) principle to temporarily store and manage function invocation (call).

Basically, it is a mechanism for an interpreter which store to keep track of its place in a script that calls multiple functions like what function is currently being run and what functions are called from within that function, etc.

When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing.

function greeting() {
// [1] Some code here
sayHi();
// [2] Some code here
}
function sayHi() {
return "Hi!";
}

// Invoke the `greeting` function
greeting();

// [3] Some code here

This is what happens when the code is run:

It ignores all functions until it reaches the greeting() function invocation.
Add the greeting() function to the call stack list.
Note: Call stack list: — greeting

Execute all lines of code inside the greeting() function.
Get to the sayHi() function invocation.
Add the sayHi() function to the call stack list.
Note: Call stack list: — sayHi — greeting

Execute all lines of code inside the sayHi() function, until reaches its end.
Return execution to the line that invoked sayHi() and continues executing the rest of the greeting() function.
Delete the sayHi() function from our call stack list.
Note: Call stack list: — greeting

When everything inside the greeting() function has been executed, return to its invoking line to continue executing the rest of the JS code.
Delete the greeting() function from the call stack list.

What causes a stack overflow?

If the stack takes up more space than it had assigned to it, it results in a “stack overflow” error or A stack overflow occurs when there is a recursive function (a function that calls itself) without an exit point. The browser (hosting environment) has a maximum stack call that it can accommodate before throwing a stack error.

function callMyself(){
callMyself();
}

callMyself();

N.B: I only write blogs for myself. I thought when I write a blog I understand the concept better.

I hope you like it, feel free to post your valuable comments, to help me improve.

--

--