Recursion Curriculum

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 ]

So this is an example given on the Curriculum and it has some explanation that the reason the numbers are pushed in ascending order is that push is executed only after the return. I get that. I can’t seem to understand why the rest of the code in the Else Condition gets executed since when n == 0 it will return .

in this code, the function call is countup(5)

note that inside the function there is const countArray = countup(n - 1);, so this part call countup(4), and it will go to next line only after the function call returns a value
this one call countup(3), and so on till countup(0) is called, which returns [] so you finally have a value for countArray and it will go to the next lines

try looking at it with this tool: http://pythontutor.com/javascript.html#mode=edit

1 Like

The function is called multiple times during recursion. The function call when n = 0 returns [], but that call occurred inside of a function call where the else clause was being executed.

1 Like

thank you very much for sharing this awesome tool and for your explanation

Thank you for your explanation. I finally got it now ^^

1 Like