Recursion lessons: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown

The code provided in this challenge is:

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]

The challenge is to do the opposite which is countdown(num) and placing the numbers in countdown order instead. I passed by just changing push to unshift. Did I cheat? I don’t feel the most comfortable with recursion so I’m curious if there’s another way to do this that involves the recursive number rising to a ceiling limit rather than decreasing to a floor limit? (I hope that analogy made sense. :smile: )

No you did not cheat, you solved the challenge.

You can click on the Get Help >> Get a Hint link to see 3 other possible solutions to this challenge.

1 Like

Try countup(n+1), at starting n should be 1, if n>5 return [];

function countup(n) {
  if (n > 5) {
    return [];
  } else {
    const countArray = countup(n+1);
    countArray.unshift(n);
    return countArray;
  }
}
console.log(countup(1));

Something like this also works. Is that what you was asking for ?

I believe the user is wanting a solution to the actual challenge that used countdown(n + 1) in the solution.

I think that would work for the specified challenge of 5, but I don’t think it would work for 10 which is one of the tests FCC runs to verify it was done properly.

Yes. That or something similar where I wasn’t just switching to a different array method, but if it works it works!

but the function call will be countup(3) and will want [1,2,3], will be countup(6) and will want [1,2,3,4,5,6]
you can’t change the behaviour of the parameter like that. If the parameter is the max number, you can’t suddenly decide it is not.

Perhaps I still haven’t explained what I’m trying to say properly. What I’m trying to say is how to design the function so that we count up to a maxNumber. The function could be modified to pass a second parameter of a starting number and a max number, but that’s covered in the lesson following this one, so I don’t think that’s optimal. The issue is as ieahleen said: the maximum is being limited by the function itself, not by a parameter passed into the function.

1 Like