DEV Community

Tetsuo TANAKA
Tetsuo TANAKA

Posted on Edited on

What Really Happens When You Call a Function? Watching the Call Stack

In this series, we use JSVisualizer, a free browser-based tool, to understand classic algorithms by watching them run. Last time we looked at conditionals.

This time the topic is functions, and the star of the show is the Call Stack view.

Where beginners get stuck

This program adds the squares of two numbers. 3 * 3 + 4 * 4 is 25.

function square(x) {
  return x * x;
}

function sumOfSquares(x, y) {
  return square(x) + square(y);
}

let x = 10;
let answer = sumOfSquares(3, 4);
console.log(answer);
console.log(x);
Enter fullscreen mode Exit fullscreen mode

What does the last line, console.log(x), print? People who've just met functions often wonder:

  • x shows up in three places. It's a parameter (a variable that receives a value passed to a function) of square, a parameter of sumOfSquares, and the let x outside. Are these the same thing or different things?
  • Where does execution go when you call a function, and how does it get back? Partway through square(x) + square(y), the program jumps into another function. How does it know where to pick up again?
  • If a function changes a value, does the change reach the outside?

JSVisualizer's Call Stack view shows you exactly this: each function call gets its own frame, which appears when the call starts and is removed from the call stack when it ends.

Seeing it in the Call Stack view

How to read it

Paste the code into JSVisualizer, press ▶ Run, and open the Call Stack tab. Then press ▷ Human (one "human-friendly" step) three times:

Call Stack view: Global holds x = 10 and more; below it, sumOfSquares(3, 4) holds x = 3 and y = 4

Each box is called a frame. Every time you call a function, a new frame is created just for that call, and the Call Stack view shows the variables that belong to each frame along with their values.

  • Global is a special box that shows the variables (and other names) outside any function. It's always at the top. square = ƒ square means there's a function named square, and answer = — means answer doesn't have a value yet.
  • sumOfSquares(3, 4) is the frame for the call we just made. Its heading shows the values that were passed in.
  • The blue outline marks the frame that's running right now.

The sumOfSquares frame has x = 3, while Global has x = 10. Same name, but they live in different places: they're two separate variables.

Calls pile up

Press ▷ Human six more times (nine in total), and look at the whole screen:

Full screen: on the left, line 2 (return x * x) is running and square(y) on line 6 has a dashed purple underline; on the right, Global has x = 10, square(4) has x = 4, and sumOfSquares(3, 4) has x = 3 and y = 4

  • On the left, line 2 inside square is running, and the call that got us here, square(y), has a dashed purple underline.
  • On the right, a square(4) frame has appeared under Global, pushing sumOfSquares(3, 4) down. New frames always appear right below Global.

Now look at x: it's 10 in Global, 4 in square(4), and 3 in sumOfSquares(3, 4). Three variables with the same name exist at the same time, with three different values.

Frames are removed

Press ▷ Human five more times (14 in total):

Call Stack view: only Global remains, with x = 10 and answer = 25

When a function finishes running, its frame is removed from the call stack. Only Global is left on screen, and answer now holds 25. Global's x is still 10. That's what the final console.log(x) prints.

What the frames reveal

1. Same name, different frame, different variable

A function's parameters and the variables declared inside it belong to that one call. Here, when square says x, it means square's parameter x. There's a variable with the same name outside, but it's a separate variable.

The region of code from which a variable can be referred to is called its scope.

Be careful: scope is a different idea from frames and the call stack. The call stack is the pile of function calls currently running, so it shows which function called which. Scope in JavaScript, on the other hand, depends not on where a function is called from but on where the function is written in the code (where it's defined). For example, square is called from sumOfSquares, but code inside square can't use sumOfSquares's y. Seeing the sumOfSquares(3, 4) frame below the square(4) frame in the Call Stack view only tells you the order of the calls; it doesn't mean square can see sumOfSquares's variables.

This is why you can write a function without worrying about what variable names its callers happen to use.

2. The newest call finishes first

Step through and watch the frames:

  1. The sumOfSquares(3, 4) frame appears
  2. The square(3) frame appears, then is removed when it finishes
  3. The square(4) frame appears, then is removed when it finishes
  4. The sumOfSquares(3, 4) frame is removed

The most recent frame is always the first to go, just like taking plates off the top of a pile. A pile that works this way is called a stack, and since this one is made of function calls, it's the call stack.

Notice that the sumOfSquares frame stays put while square runs. That's how execution can pick up where it left off in square(x) + square(y).

One note: this article is about ordinary synchronous calls, where the caller waits for the function to finish before moving on. With asynchronous code (setTimeout, async/await), the rest of a function runs later as a separate job, so "frames pile up and come off the top" isn't the whole story. JSVisualizer doesn't reproduce real asynchronous behavior either, so this series sticks to synchronous code.

3. Assigning to a parameter doesn't change the caller's variable

What does this program print?

function addOne(n) {
  n = n + 1;
  return n;
}

let n = 10;
addOne(n);
console.log(n);
Enter fullscreen mode Exit fullscreen mode

Not 11. Pausing inside addOne shows why:

Call Stack view: Global has n = 10, and addOne(10) has n = 11

The n in the addOne(10) frame has become 11, but Global's n is still 10. A function doesn't receive the variable itself. It receives a copy of its value. With numbers like this, assigning a new value to the parameter inside the function has no effect on the caller's variable. (With arrays and objects, the caller and the function can end up sharing the same object; we'll get to that later in the series.)

Call Stack view: the addOne frame is gone, only Global with n = 10 remains, and the console shows 10

When the function ends, the addOne frame is removed from the call stack. return n hands back 11, but the caller doesn't use that value, so Global's n stays 10. Write n = addOne(n); and the returned 11 is stored in Global's n.

Try it yourself

Open the link below and press ▶ Run; the Call Stack view opens. Step forward with ▷ Human (the h key) and back with ◁ Human (H).

▶ Open in JSVisualizer (sum of squares, Call Stack view)

To change the code, press ✏ Edit. Before each run, predict how the frames will behave:

  • Change sumOfSquares(3, 4) to sumOfSquares(square(2), 4). Which frame appears first?
  • Add console.log(y); at the very end. What happens, and why?

One more program to play with:

Wrapping up

  • Calling a function creates a frame just for that call. When the call ends, the frame is removed from the call stack.
  • A function's parameters and local variables are separate for each call, and separate from any outside variable with the same name. The Call Stack view shows them side by side, with different values. Which variables code can refer to (its scope) depends on where the function is written, not on who called it.
  • The newest frame is the first to go. A function receives a copy of a value, so assigning to a number parameter inside doesn't change the caller's variable.

Next up: how expressions are evaluated. We'll use the Expr view to see the order in which a complicated expression like a + b * c > 10 && d gets worked out.

Top comments (2)

Collapse
 
mp3sss31 profile image
mp3sss •

The call stack view is the clearest way to make recursion and stack overflow click visually — watching frames push and pop beats reading a textbook diagram. One worth adding for beginners is where the model breaks down: async callbacks and promises don't live on the same synchronous call stack, so after an await the frame you resume in isn't the one you left. Pairing the visualizer with a stack-depth or maximum-call note makes that transition explicit when the exercises move past plain functions.

Collapse
 
tntetsu profile image
Tetsuo TANAKA •

Thanks for the thoughtful comment! You're right that async is exactly where the "one stack of frames" picture stops matching reality. After an await, the rest of the function runs later as a new job, with only the event loop beneath it.

One caveat about the tool itself: JSVisualizer runs async/await as a synchronous simulation, so the Call Stack view would show the function picking up in the same frame. That's the very misconception you describe. Real async APIs like setTimeout and fetch aren't supported. I've added a note to the article saying the series sticks to synchronous code for that reason.

On stack depth: the recursion article (part 6) shows what happens when a function never stops calling itself and the stack overflows.