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

244
Views
WHy in my recursion function the code after the if condition is repeated?
// program to count down numbers to 1
function countDown(number) {

  // display the number
  console.log(number);

  // decrease the number value
  const newNumber = number - 1;

  // base case
  if (newNumber > 0) {
    countDown(newNumber);
  }
  console.log(newNumber);
}

countDown(4); 

// output => 4 3 2 1 0 1 2 3

I can't visualize what happens after the if condition. I mean I understand that there is "loop" with countDown(newNumber). But I don't understand why there is the output 0 1 2 3. I know I can put an else keyword, but I'd like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber).

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

0

Your recursive call does not end the execution of the function.

So what happens is that if you call newNumber(2) it executes the first console.log, logging 2. Then it assigns newNumber to 1. Then your recursion happens, printing 1. Inside the recursive call newNumber becomes 0, so no more recursion. Instead, the second print inside the recursion prints 0. Now your recursion returns, and the second print outside of your recursion prints the current value of newNumber in the non recursive call. And that is 1.

So you get 2 (outside recursion) 1 (inside) 0 (inside) 1 (outside)

about 4 years ago · Juan Pablo Isaza Report

0

You can simplify your function.

function countDown(number) {

  if (number > 0) {
    console.log(number);
    countDown(--number);
  }

}

countDown(4);

about 4 years ago · Juan Pablo Isaza Report

0

this way ?

countDown( 4 )

// program to count down numbers to 1
function countDown(num)
  {
  if (num<1) return
  console.log(num)
  countDown(--num)
  }

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!