DEV Community

Cover image for What’s the call stack?
Colby Cardell
Colby Cardell

Posted on

What’s the call stack?

JavaScript is single-threaded, meaning it has a single call stack, meaning it can do one thing at a time. The call stack is basically a data structure which records where in the program we are. If we step into a function, we push something onto the stack. If we return from a function, we pop off the top of the stack.

When our program throws an error, we see the call stack in the console. We see the state of the stack (which functions have been called) when that error happened.

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).

Let’s break down our definition:

LIFO: When we say that the call stack, operates by the data structure principle of Last In, First Out, it means that the last function that gets pushed into the stack is the first to be pop out, when the function returns.

Example:

function firstThing (){
return "FIRST THING"
}
function secondThing(){

return firstThing() + " SECOND THING"
}
secondThing();

//FIRST THING  SECOND THING
Enter fullscreen mode Exit fullscreen mode

So this code is really simple. There is a function called 'firstThing', and another one called 'secondThing'..We are calling 'secondThing' 1st, which returns 'firstThing' ➕ the string "SECOND THING".

Summary

An ordered set of stack frames, most recently invoked function is on the top of the stack. The bottom of the stack is the 1st function invoked, the stack is processed from top to the bottom

Top comments (1)

Collapse
 
codefinity profile image
Manav Misra

This is very nicely written! I especially like the formatting and code examples.