Home > database >  Whats going on here im trying to wrap my head around recursion and this return function
Whats going on here im trying to wrap my head around recursion and this return function

Time:10-17

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

So far I understand that by me setting countArray to the function it decides to call itself until n = 0 . At that point it returns an empty array to countArray but i just don't understand what happens after that point that gives this odd outcome of the numbers being ordered, i assumed it would just push the current value of N being 0 to the array but it clearly doesn't...

Does anyone know what's going on here?

CodePudding user response:

0 is not pushed to the array because of the if condition. At that point your countArray is set to [].

When using recursion interpreter needs a way to be able to understand in which order these functions have to be processed.

When your script runs first time, the interpreter creates a global execution context and pushes it to the execution stack.

Once it finishes, the engine executes the function whose execution context is at the top of the stack first. In your case n=1. It pushes it to the array, pops it from the stack then continues n=2 and so on until it reaches the last one in the stack n=5

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    console.log(n)
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related