Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
Whats going on here im trying to wrap my head around recursion and this return function

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!