Use Recursion to Create a Countdown

Hi everyone,

I’m very sorry if this has been asked a million times but I’d really appreciate if someone could help explain the code to me.

In the example function for countup.

  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));
type or paste code here
  1. I understand that countup(0) is the first to return the array as 0<1 - so the array is returned empty []. However, why is it that countup(1) is the next to receive the empty array?

  2. Does countup(x) have any actual meaning - as in it just seems to hold the value, which is then pushed to the end of the array? I’m not entirely sure why the code works, but logically, if countup(1) is next after countup(0) then it would just add its value to the end of the array after .push method has been executed. So I can understand why it would be in ascending order - I’m just not sure why countup(1) is next to be called after countup(0).

  3. This probably sounds really silly, but in the example, n is 5. so how exactly does this part of the code work:

const countArray = countup(n - 1);
    countArray.push(n);
  1. 5 -1 = 4. so countup(4) but does this mean the original value of n (5) is pushed or is it the new value (4) of n that is pushed?

  2. Am I right in understanding that the push method is executed immediately after, countArray.push(n) is executed. So wouldn’t the starting value n =5 -->countup(4) end up pushing the value 4, not 5? I don’t understand where the 5 comes from in the array…

I am very sorry for the long-winded post, but I’ve tried asking ChatGPT to explain it and I still don’t understand.

Thank you.

if you console.log( ) the countArray before push( ):

console.log(countArray)

it return this:
image

Remember that recursion method will keep calling itself, until the base case/stop criteria. Then it returns one layer by one layer upward. The first call of recurisve , will be the last to execute.

Then, it sounds like this to me:

n = 5, call countup (4)
n = 4, call countup (3)
n = 3, call countup (2)
n = 2, call countup (1)
n = 1, call countup (0)
n = 0, no more calling // because it is a base case.

n = 0 , countup(n - 1) → return [ ]
n = 1 , countup(n - 1) → return [1 ]
n = 2 , countup(n - 1) → return [1, 2]
n = 3 , countup(n - 1) → return [1,2,3]
n = 4 , countup(n - 1) → return [1,2,3,4,]
n = 5 , countup(n - 1) → return [1,2,3,4,5]

Hope this helps. If my concept is incorrect, please enlighten me too :smile:

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