What is a call stack in JavaScript?

Tejaaswini Narendra
3 min readNov 5, 2020

--

Knowing the core fundamentals of the language becomes essential to understand how certain things work in order to write a clean and efficient code. Here is a brief understanding of call stack in JavaScript.

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

Let’s say we have a called a function. Now this function call could result in ’n’ other function calls which could in turn have cascading functions. Now JavaScript is synchronous and single threaded by nature, meaning it can just do one job at a time. Ergo JavaScript needs to keep track of the history of things also to keep track of the of which functions are invoked but not yet called and also a list of what has to returned. This is where Call Stack comes to rescue.

Well as the name suggests Call Stack is noting but a stack which follows the LIFO (Last In First Out) principle. When you call a function, the JavaScript engine creates a function execution context. Now every function has it individual function execution context (FEC). Whenever a function is called, the FEC is called and is pushed to the top of the stack and the execution takes place. The most recent function call is always on the top (remember LIFO). The very first function call invoked is always the main function. This could be regarded as the most basic, top level function call in JavaScript.

Let’s look at an example.

Once the function is executed, the corresponding FEC is popped off the call stack and the JS engine resumes execution from where it left off. Confusing much? Let’s take a look at an example:

So what exactly happened in here? Let’s head to Chrome dev tools and debug behind the scenes.

When we have a look at Call Stack, we see an Anonymous function pointing to line number 15. This is the main function that is being called.

Now second() is called and is pushed into the stack. This function calls first(). Thus first() is added to the stack next.

Here function first returns “First” and is popped out of the stack. After this second() is popped and later main() is popped out. This is how call stack works!

Now there’s a catch, what if there’s a recursive function? What would happen? Consider the following example,

What could be the possible output?

This gives what is known as “Maximum call stack exceeded” error. Chrome allows 16,000 frames as the max call stack size. So the above example is run 16,000 times and returns nothing.

Thus call stack is nothing but an ordered set of stack frames which is processed from top to bottom.

--

--