Javascript Recursion

RMAG news

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);

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.

Leave a Reply

Your email address will not be published. Required fields are marked *