Use of Recursion

I dont understand this code.

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 ]

//How can it return an array of numbers since the ā€˜ā€™ was never created ??

Blockquote

I think figured out why.
Because once ā€˜nā€™ becomes less than 1 it returns the and all numbers got in forming an array of numbers.
if (n < 1) {
return ;

2 Likes

That is correct. In the else clause, each call to the function with reduced arguments has to return before pushing the next number.