The Startup
Published in

The Startup

JavaScript Call Stacks — An Introduction

If you’re in the software world, you’ve heard of stacks. Stackoverflow, anyone? If you’ve always wondered what that actually means, you’re in the right place.

In broad terms: what is a stack?

I happen to be intimately familiar with pancake stacks, which is the first thing that comes to mind when I hear the word “stack.” Luckily, it is a fitting visual description for a software stack.

A stack of pancakes meant to represent a call stack
~ this looks like a sticky situation ~

It is a data type similar to an array that behaves as a collection of elements. In this visual example, each pancake represents some element, which has been added to the top of the stack, and can also only be removed from the top. Because of this linear structure, stacks are also referred to as “LIFO” — which stands for “last in, first out.”

Stacks have two main operations: “push” and “pop.” If you are familiar with arrays, you’ll be happy to know that these methods are exactly what you think: “push” adds an element to the top of the stack, and “pop” removes the most recently added element from the top. Unlike an array (or a stack of pancakes), it is not possible to access an element from the bottom or middle without first removing the ones on top of it.

Is that the same as a JS call stack?

A Javascript call stack is an example of a stack data structure. In this stack, the elements are function invocations. Every time a function is invoked, it is added to the stack. If it has a nested function, that nested function will get added to the top of the stack as well, and so on. You can think of it as a to-do list of sorts for Javascript. It’s important to remember that Javascript is largely a single-threaded process, meaning that it processes one command at a time. (Asynchronous actions are handled differently and I highly recommend this video if you’d like to learn more about that.)

Once all functions that need to run in a given script have been pushed onto the top of the stack in order of invocation, Javascript starts resolving them in order from top to bottom and popping them off the stack.

In the gif below, you can see that the function printSquare is invoked at the bottom of the screen. The printSquare function is added to the call stack, but it can’t be resolved until it receives the return of its nested function calledsquare. The square function is now added to the call stack, but it can’t be resolved until it receives the return of its nested function called multiply. The multiply function gets pushed onto the top of the stack, and since it has a return statement that can be returned right away, it goes ahead and completes, and gets popped off the top of the stack. The call stack continues in this manner, popping functions off in reverse of the order in which they were called.

Researching this blog post was a bit like managing my own call stack. As I started one line of research, it inevitably brought up a nested question, which I needed to understand before continuing; during the research of that second question, I came upon another topic I needed to investigate before continuing with the previous subject… Resolving the deepest question allowed me to go back up one level and resolve the previous question, and so on, until I found myself back at level one, ready to write this blog!

Can we try it ourselves?

The Chrome browser has a really robust dev tools panel, that merits its own blog post. One of the things you can do with it is step through code line by line and see it getting pushed onto the stack. To open it, right click (or type Cmd+ option + j) on any web page in Chrome, choose the Inspect option, and the Sources tab on the top. I made a small video with a stack call demonstration using the breakpoint and step through tools. The breakpoint is added to the aDayInTheLife function invocation, which pauses the code and allows us to step through each cascading function. As you can see, the functions are added to the stack from bottom to top, then are resolved from top to bottom as the functions receive their return values and are able to be resolved. Ultimately, the string “Made the bus in seconds flat” is passed all the way back to the original aDayInTheLife function and is returned in the console at the very end once the stack has been cleared.

A gif of functions being added to the call stack and then popped off one by one

So what is this stack overflow thing?

The basic premise is that computer memory is finite, and if there are more elements pushed onto the stack than there is space for, the stack will “overflow.” The most common cause of a stack overflow situation is infinite or very deep recursion. A recursive function is one that calls itself — visit this blog for a nice explanation on how recursion works. An example that was easier for me to visualize than recursion was picturing two functions that are calling each other. The first function adds the second function to the call stack, the second function adds the first function to the call stack and so on. Since nothing is ever returned or resolved, the stack will overflow.

two functions that call each other over and over — an example of recursion
Two functions calling each other will lead to a stack overflow
image of the call stack when two functions call each other
The overflowing stack calls

As you can see, the chrome dev tool has error handling for this and will error out after 16,000 frames (call stack elements).

chrome dev tool error when maximum call stack size is reached
The Beatles saying Hello & Goodbye for infinity — no error handling needed :)

Stackoverflow — the website — got its name from a poll done in 2008 when the creators of the developer community website were naming their creation. Some of the other options were “humbledeveloper.com” and “writeoncereadmany.com.” 25% of about 7,000 votes went to “stackoverflow.com,” making it the winner, and I, for one, think they chose the best one.

Where can we learn more?

Here are some videos and links that I found really helpful for visualizing and understanding the call stack:

Thanks for reading my blog! May your cup runneth over but your stack never overfloweth.

I would love to connect on LinkedIn and Twitter!

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

How to pass Rails instance variables into Vue components

Making GET and POST HTTP request to Algorand using PureStake API

Double URL-encoded XSS

ADVANTAGES OF TRADING VOLATILE INDICES

2: Our 1st ROS 2 TypeScript Program

Fix husky: lint-staged not running on precommit

Making Flow error suppressions more specific

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Julia Zolotarev

Julia Zolotarev

Software Engineer; hospitality enthusiast; lover of ice cream.

More from Medium

Ternary Operators in Javascript​ : Short-hand Syntax

A Look at JavaScript Scopes

PureScript: A Haskell-like Language that Compiles to JavaScript

The Quirks and Peculiarities of NaN