DEV Community

Cover image for Javascript Recursion
Ticha Godwill Nji
Ticha Godwill Nji

Posted on

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) {
    } else {
        // Progress towards base case: decrementing n
        countdown(n - 1);

// Example usage
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.

Top comments (0)