Home > Software design >  Use Recursion to Create a Countdown | FreeCodeCamp Recursion problem
Use Recursion to Create a Countdown | FreeCodeCamp Recursion problem

Time:09-17

var a=[];
// Only change code below this line
function countdown(n){
  
  if(n>=1){
    
    countdown(n-1);
    console.log(n);
    a.push(n);
    return a;
  }
  else{
    return [];
  }
}
console.log(countdown(5));

Here I want to know after the recalling of the countdown function why the n is printed like 1,2,3,4,5? It should be 5,4,3,2,1?

CodePudding user response:

In the initial call to countdown (where n=5) you recursively call countdown and then print n.

CodePudding user response:

Switch the order of console.log(n); and countdown(n-1); and you will have expected behavior.

var a=[];
// Only change code below this line
function countdown(n){
  
  if(n>=1){
    
    console.log(n);
    countdown(n-1);
    a.unshift(n);
    return a;
  }
  else{
    return [];
  }
}
console.log(countdown(5));

  • Related