DEV Community

Cover image for Javascript Recursion
Ticha Godwill Nji
Ticha Godwill Nji

Posted on

1 1 1 1

Javascript Recursion

A recursive function in Javascript is a function that calls itself over and over until a certain base condition is attained.

In a recursive function, there are two important things to note.

  • The base condition: This is a condition that determines when the function should stop otherwise it will be an indefinite recursion without the base condition.

  • Progress towards the base case: Each recursive call should move the functions towards the base case.

function countdown(n) {
    // Base case: when n reaches 0, stop recursion
    if (n === 0) {
        console.log("Blastoff!");
        return;
    } else {
        // Progress towards base case: decrementing n
        console.log(n);
        countdown(n - 1);
    }
}

// Example usage
countdown(5);
Enter fullscreen mode Exit fullscreen mode

Explore more on my Youtube channel

  • The base case is when n reaches 0. At this point, the function logs "Blastoff!" to the console and returns.

  • The progress towards the base case is achieved by decrementing n in each recursive call (countdown(n - 1)), bringing it closer to the base case. Eventually, n will reach 0, satisfying the base case condition, and the recursion will stop.

Note that the factorial function can be written as a recursive function call.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

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

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay