DEV Community

Tetsuo TANAKA
Tetsuo TANAKA

Posted on

How Many Times Does a Nested Loop Really Run? Seeing Execution Counts in Color

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

This time the topic is nested loops, and the star of the show is the Heatmap view.

Where beginners get stuck

This program prints a multiplication table:

for (let i = 1; i <= 9; i++) {
  let row = "";
  for (let j = 1; j <= 9; j++) {
    row = row + (i * j) + " ";
  }
  console.log(row);
}
Enter fullscreen mode Exit fullscreen mode

A loop inside a loop is called a nested loop. When you first meet one, it's easy to wonder:

  • Which changes first, i or j? What does j do while i is 1?
  • How many times does let row = "" run? It's inside the outer loop but outside the inner one.
  • How many times does the innermost line run in total? And how fast does that grow when the numbers get bigger?

When you think about a program's efficiency, lines that run over and over are one of the first places to look. But you can't tell how often a line ran just by reading the code. JSVisualizer's Heatmap view shows how many times each line ran, in color and in numbers.

Seeing it in the Heatmap view

How to read it

Paste the code into JSVisualizer, press ▶ Run, and open the Heatmap tab. Press the End key to jump to the end:

Heatmap view: line 1 ran 20 times, line 2 ran 9 times, line 3 ran 180 times, line 4 ran 81 times, and line 6 ran 9 times. Line 3 is the darkest orange

  • Line color: the more often a line ran, the darker its orange.
  • The counts: each line shows "runs so far / total runs". The first number climbs as you step forward.
  • The dots on the right: when that line ran, with time flowing from left to right. The lines between dots show execution moving from one line of code to another.

Line 2, let row = "", ran 9 times, and line 4, the body of the inner loop, ran 81 times. There's 9 × 9 = 81, right on the screen.

The for lines have bigger counts because the initialization, the condition check, and the update are all counted. Line 3's 180 is 9 initializations (let j = 1), 90 condition checks (j <= 9), and 81 updates (j++). Note that this differs from the Control Flow view in an earlier post, which counts only the condition checks on a for row.

Looking partway through

Go back to the start (the Home key) and press ▷ Human (one "human-friendly" step) 30 times:

Heatmap view: line 1 at 2 of 20, line 2 at 1 of 9, line 3 at 18 of 180, and line 4 at 9 of 81. Only the leftmost dots are blue and the rest are gray

Blue dots have already run, gray dots are still to come, and the red dot is where you are now. Line 4 now reads 9 of 81: while i was 1, the inner loop went around 9 times.

What the colors reveal

1. The inner loop starts over for every outer pass

In the dots on the right, line 4 forms clusters of 9, and there are 9 of those clusters. Between clusters sits a single dot for line 6, console.log(row).

Each step of the outer loop runs the entire inner loop from 1 to 9. The way a nested loop works is right there in the pattern of dots: j goes from 1 to 9 while i is 1, and only then does i become 2.

2. Double the size, four times the work

When the inner loop runs the same number of times for every pass of the outer loop, as it does here, the body runs (outer count) × (inner count) times. If you replace both 9s with n, the body runs n × n times:

n Runs of the body
3 9
6 36
12 144

Each time n doubles, the count quadruples. When the count grows in proportion to the square of n as n gets large, that growth is written with the notation O(n²) ("big O of n squared"). You won't notice it while n is small, but the count climbs steeply as n grows.

3. Look at the dark lines to cut wasted work

A prime is a number of 2 or more that can only be divided evenly by 1 and itself. This program counts the primes up to 25:

let count = 0;
for (let n = 2; n <= 25; n++) {
  let isPrime = true;
  for (let d = 2; d < n; d++) {
    if (n % d === 0) {
      isPrime = false;
    }
  }
  if (isPrime) {
    count++;
  }
}
console.log(count);
Enter fullscreen mode Exit fullscreen mode

n % d is the remainder when n is divided by d. A remainder of 0 means it divides evenly, so n isn't prime.

Heatmap view: line 4 is the darkest at 600 runs, line 5 ran 276 times, and line 6 ran 38 times. The console shows 9

There are 9 primes, and the divisibility check on line 5 ran 276 times, which is why lines 4 and 5 are so dark. The inner loop gets longer as n grows, and the runs add up. (The dots show only the last 200 runs of each line, so the dots for lines 4 and 5 start partway across.)

But there's wasted work here:

  • As soon as one divisor turns up, we know n isn't prime. There's no need to keep looking.
  • If n isn't prime, at least one of its divisors other than 1 and n itself is at most the square root of n. So it's enough to check while d * d <= n. For example, 21 is 3 × 7. You don't need to go all the way to 7: it divides evenly at 3, which is below the square root (about 4.6).

So let's change the inner loop. break exits a loop immediately:

  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) {
      isPrime = false;
      break;
    }
  }
Enter fullscreen mode Exit fullscreen mode

Heatmap view: line 4 ran 90 times, line 5 ran 36 times, and lines 6 and 7 ran 15 times. The console shows 9

The answer is still 9, but the divisibility check dropped from 276 runs to 36. The dark lines point to where the waste might be, and the numbers confirm that your fix worked. The heatmap shows how many times each line ran, not how long it took, but that's still a good lead when you're hunting for wasted work.

Try it yourself

Open the link below and press ▶ Run; the Heatmap view opens. Press End to see the totals, or step with ▷ Human (the h key) and watch the numbers climb.

▶ Open in JSVisualizer (multiplication table, Heatmap view)

To change the code, press ✏ Edit. Before each run, predict the counts:

  • Change the inner j <= 9 to j <= i. What shape does the table take? How many times does line 4 run?
  • Change both 9s to 18. How does line 4's count compare with 81?

The prime programs are here too:

One thing to know: JSVisualizer stops a program after 50,000 steps, so that a loop that never ends can't freeze the page. These are fine-grained steps that count every part of every expression. If you change the first prime program to n <= 100, it goes over the limit and you'll get an error saying the maximum number of steps was exceeded.

Wrapping up

  • The Heatmap view shows how many times each line ran, in color and in numbers. The dots on the right show when it ran.
  • When the inner loop runs the same number of times on every outer pass, the body runs (outer count) × (inner count) times, so doubling n means four times the work: O(n²).
  • Dark lines are where to look for wasted work. They show run counts, not time, but the counts also show whether your change helped.

Next up: recursion. We'll compute powers with a function that calls itself, and use the Subst view to watch the expression expand.

Top comments (1)

Collapse
 
alexshev profile image
Alex Shev •

Visualizing execution counts is a great bridge between syntax and cost. One useful extension would be to change the input shape from balanced to skewed collections: it makes clear why Big-O is a bound, while the actual count depends on loop guards, early exits, and data distribution. That distinction pays off later in query and algorithm tuning.