Skip to content
Advertisement

why isn’t recursion working? i am trying to display n to 1 series

Javascript Recursion


why isn’t recursion working here? i see coundown(n-1); isn’t working for some reason. I want to display [5,4,3,2,1]

   function countdown(n){
    if (n<1){
    return [];

   } else {

    var myArr = [];
    myArr.push(n);
    countdown(n-1);
    return myArr;

   }
  }
  countdown(5);

Advertisement

Answer

Your code creates a new array at every recursive call, puts one value in it and returns it. Nothing is done with the array that is returned, as each execution instance of your function seems only interested in its own array, which it returns.

You need to create one array, and extend that while backtracking out of recursion, each time making sure you capture the array that the recursive call gives you back as return value:

function countdown(n) {
    if (n < 1) {
        // This is the only time you should create an array:
        return [];
    } else {
        // Get the array that comes out of recursion!
        let myArr = countdown(n-1);
        // Prefix the current value into it
        myArr.unshift(n);
        // And pass that extended array further up 
        // the recursion tree:
        return myArr;
    } 
}

console.log(countdown(5));

Written a bit more concise it could become:

const countdown = (n) => n < 1 ? [] : [n].concat(countdown(n-1));

console.log(countdown(5));

And without recursion:

const countdown = (n) => Array.from({length: n}, (_, i) => n - i);

console.log(countdown(5));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement