Home > Net >  WHy in my recursion function the code after the if condition is repeated?
WHy in my recursion function the code after the if condition is repeated?

Time:02-21

// 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).

CodePudding user response:

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)

CodePudding user response:

This might help you to visualize that:

http://latentflip.com/loupe/?code=Ly8gcHJvZ3JhbSB0byBjb3VudCBkb3duIG51bWJlcnMgdG8gMQ0KZnVuY3Rpb24gY291bnREb3duKG51bWJlcikgew0KDQogIC8vIGRpc3BsYXkgdGhlIG51bWJlcg0KICBjb25zb2xlLmxvZyhudW1iZXIpOw0KDQogIC8vIGRlY3JlYXNlIHRoZSBudW1iZXIgdmFsdWUNCiAgY29uc3QgbmV3TnVtYmVyID0gbnVtYmVyIC0gMTsNCg0KICAvLyBiYXNlIGNhc2UNCiAgaWYgKG5ld051bWJlciA+IDApIHsNCiAgICAgIGNvdW50RG93bihuZXdOdW1iZXIpOw0KICB9DQogIGNvbnNvbGUubG9nKCdwb3RhdG9zJykNCiAgY29uc29sZS5sb2cobmV3TnVtYmVyKTsNCn0NCiANCmNvdW50RG93big0KTsg!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4=

CodePudding user response:

You can simplify your function.

function countDown(number) {

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

}

countDown(4);

CodePudding user response:

this way ?

countDown( 4 )

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

  • Related