countUp with recursion

**I don’t understand the running of this code i expected that the array value will decrease from n to 1 but it’s the opposite can someone explain it to me please ? **

Your code so far


//Only change code below this line
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 ]

Challenge: Use Recursion to Create a Countdown

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

1 Like

a call to countup(n) is actually pushing the number n into the back of array. In the code you can see that countup(n) is calling countup(n-1) as a subroutine, which would push (n-1) into the array(Actually it would also recurse to create array [1,2,3] and then push 4 to update array to [1,2,3,4]). Now since n-1 is being pushed into array before n, so the elements of array would be in increasing order and not in decreasing order.

Let up try to simulate the call stack :
countup(5) -> countup(4) -> countup(3) -> countup(2) -> countup(1) -> countup(0)
At this point, countup(0) would return an empty array.
After this the call would go back to second last line of countup(1), which would push 1 into the array. So array becomes [1]. After this call would return to countup(2), which would add 2 to array so array becomes [1,2]. This continues till countup(5) is executed and the array becomes [1,2,3,4,5].

7 Likes

Thank you very much for this explanation

No problem :slightly_smiling_face:

1 Like