Countdown with Recursion - please help me understand the example

I’ve been trying to understand step by step what is happening in the example to create an array counting up from 1 to n. I’ve read all the forum posts over and over and it’s still not clicking.

The code is:

function countup(n) {
  if (n < 1) {
    return [ ];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}

Using the example of n = 3, my understanding is that it executes to the line…

const countArray = countup(n - 1);

… which calls the function again (it jumps back up to the very first line). So basically it keeps (re)calling the function with 2, then 1, then 0 - the base case.

This is where my confusion is. As it recalls the function, are 2 and 1 being returned in an array? Or does it hit the base case, return an empty array, and then start working backwards, pushing 1 into the empty array, then 2, then 3?

The explanation on the page basically says an array of [1, 2, …(n - 1)] is returned just through the recursion - without ever having executed the…

countArray.push(n)

…line once. The .push() line only executes once and pushes n (in this case 3) onto the end of the array.

Another explanation/visualization on the forums makes it seem like .push() line is executed for every iteration of n, but only after the base case is reached. So it hits the base case, creates the empty array then for some reason works backwards, executing the .push() line with 1, then 2, all the way up to n.

Might be easiest to ask if the line…

countArray.push(n);

…is executed once at the end for n, or if in this case it would be executed 3x - pushing 1, then 2 then 3 into the array?

WARNING: I’m so new I don’t know if my question or explanations even make sense

This is your misunderstanding. Each function call is separate.

countup(3) needs to first know the result of countup(2)

countup(2) needs to know the result of countup(1)

countup(1) needs to know the result of countup(0)

countup(0) is

After countup(0) returns, 1 is pushed onto the array, resulting in [1]

After countup(1) returns, 2 is pushed onto the array, resulting in [1, 2]

And so on

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.