At what point is countArray defined as an array?

I’m a bit confused as to when countArray becomes an array. When it is declared it seems to be declared as an integer, but then it clearly isn’t as “n” is then pushed to it. Can anyone help explain at which point countArray becomes an array? Thanks

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    return countArray;
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Function countup(n) will return an empty array when n < 1.
Otherwise you are stuck in a recursive loop.

return countArray never return anything, because you never get to that point in your algorithm.

Try to write every step of this on a piece of paper, starting at n == 3.

countup(3) ->
if (3 < 1) ... it is not, so skipping if block ... ->
else ->
const countArray = countup(3 - 1) ... recursive call...
we go to.... ->
countup(2) ... ->

You should understand it when you work through your algo like this.

Appreciate the response but when I run this code I get the output [1,2,3,4,5], meaning that the countArray surely is being reached. To clarify, my question is how does countArray become an array if it is never defined as an empty one?

Ok I figured it out I think.

The empty array is created when countUp(0) is called, and it is assigned to countArray. The numbers are not added to countArray until the base case is met.

1 Like

You are right, I made a mistake.
Sorry for adding to your confusion.

Glad you worked it out.

1 Like

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