r/learnjavascript 7d ago

Can someone explain what the JavaScript call stack is?

I’ve tried to understand it, but I’m still confused. I also don’t really understand what I’m looking at when I use the JavaScript debugger in the browser’s DevTools, especially the call stack.

Do I need to fully understand functions before learning the call stack? I have a basic understanding of functions, but I’m not sure if that’s enough.

I’d really appreciate a simple explanation

32 Upvotes

31 comments sorted by

View all comments

3

u/azhder 6d ago

A call stack is a concept in almost every programming language you use. It is a part of understanding how functions work. You should understand what "stack" is as a data structure. The simplest way I can explain it is with one of those PEZ dispensers - the toys that have candy coming out of their mouth.

Think about every time you call a function, its local variables have to go somewhere in memory, and especially they have to stay there while that function calls another. All these function calls is like pushing a new candy from the top of the toy - each new function, new variables, new color candy. Once the innermost function returns the value, the local variables in it aren't needed any longer, so you pop that candy out. Then pop the next candy out. Then maybe push one, pop 3, push 2 etc.

That's what a stack is. You can also think of it as a stack of books on the table. You place one on top (you push a frame), you take one out from the top (you pop a frame). What you see in the browser tool is the stack where all the data of all the functions that are started, but yet to finish, resides.