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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay