DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Create a countdown using recursion (FreeCodecamp notes)

Below is an example on how countup is down using recursion

unction countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));
Enter fullscreen mode Exit fullscreen mode

The above function is best explained here https://www.youtube.com/watch?v=p-cj4Vh8cMg

The important thing to note is , that the array elements start adding from 1 onwards , the countup(4) waits till countup(1) is done.

Use the above as an example and create a countdown function so it returns n to 1 numbers in an array when we pass n in countdown(n)

Things to consider, if you have no idea about unshift, you would try to add an element to an array by declaring a new array everytime the function is called , and it is not gonna work, but if you have an idea on how to use arguments you could solve this as follows

function countdown(n, newArr=[]) {
    if (n <= 0) {
        return newArr;
    }
    newArr.push(n);
    return countdown(n - 1, newArr)
}

console.log(countdown(5));
Enter fullscreen mode Exit fullscreen mode

So thats how you pass the argument array with its elements in the recursive function.

Now the shortest /imo best solution is using unshift in array methods as below , unshift does the same as push but in the opposite order , so it works out well.


function countdown(n) {
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.unshift(n);
    return arr;
  }
}
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)