Recursion challenge with n-1 argument

When countup(5) is called can someone please tell me how the number 5 gets into the array if the else statement goes straight to the recursive calling of the function with the argument n-1? Doesn’t that make the first element in countArray 4? Thanks!

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

When you call countup(5) it will hit the else statement and make the recursive call. But then what does it immediately after making the recursive call?

So you’re saying at the push statement, n is still 5?

I think you can answer that question :slight_smile: I don’t see anywhere in that function body where the value of n changes. Do you?

K thanks for your time

Just to be clear, it is not after “making” the call, but after finishing with it.

The whole thing might be clear if you understand how call stacks work. There is probably a good video on it. But, during that first call to the function, when it encounters the next function call, the “environment” of that current call gets “frozen” on the call stack and a new function begins. This happens 4 times until the last (5th call) happens and that function call can actually finish. Then JS looks on the latest thing on the call stack and finishes that, etc., turtles all the way down. It’s like it wraps itself up with incomplete function calls until it gets to the end and then unwraps, finishing the function calls.

If you run it this way:

function countup(n) {
  console.log(n, '... entering countup');
  if (n < 1) {
    console.log(n, '... n < 1, returning []');
    return [];
  } else {
    console.log(n, '... n >= 1, making recursive call with n');
    const countArray = countup(n - 1);
    console.log(n, '... back from recursive call');
    countArray.push(n);
    return countArray;
  }
}
1 Like

I’ve been trying to figure out how to write code to keep track of n like that! Thank you! I will study this. I’ve read some stuff about stacking but it’s not clear yet. Appreciate this very much!