-1

I am assuming that this program should give the output [5,4,3,2,1] but it is giving [1,2,3,4,5]. Why this is happening? How the recursion is working here? Please explain me?

function countup(n) {
  if (n < 1) {
    // It is my base case
    return [];
  } else {
    // This is my recursive function
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}

console.log(countup(5));
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 2
    This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? – David Aug 03 '23 at 11:20
  • Because you are only pushing the current `n` onto your array, _after_ you created this array by calling your function for the next lower number ... So the initial `5` only gets pushed to the end of the array, that has already been built for `countup(4)`. And that `4` again only gets pushed to the end of the array, that resulted from calling `countup(3)`. Etc., pp. – CBroe Aug 03 '23 at 11:26
  • 1
    Normally, these operations would have to happen in opposite order - you push the `5` to the array first, and then you _append_ the result of `countup(4)` to that array. But in this instance, you can fix it by using `countArray.unshift(n);` instead - which pushes an element to the _front_ of an array. – CBroe Aug 03 '23 at 11:26

1 Answers1

2

It first goes deep in recursion, until reaches n < 1, and only than starts to push elements to array from deepest iteration to shallowest:

countup(2);
\
 | n < 1 == false // 2 < 1
 | countup(n - 1) // 2 - 1 = 1
  \ 
   | n < 1 == false // 1 < 1
   | countup(n - 1) // 1 - 1 = 0
    \
     | n < 1 == true // 0 < 1
     | return []
    /
   | countArray.push(n); // push(1)
   | return countArray // [1]
  /
 | countArray.push(n); // push(2)
 | return countArray // [1, 2]
/
console.log() // [1, 2]
Justinas
  • 41,402
  • 5
  • 66
  • 96