Recursion

Recursion is a coding architecture where the solution to solving a problem is by iteratively calling smaller versions of itself.

The parameters may change over each iteration but the function or procedure remains the same. A basic example may be when walking a folder structure from parent to child to grandchild until the deepest folder is reached. Each iteration my be reading the folder name or counting the files within each folder, for example.

In Javascript this is a simple routine to code, simply a function that calls itself. The concept can be tough to grasp, but once learnt it can really tidy up your code a be a really useful tool. There are two types of recursion, Direct Recursion and Indirect Recursion.

Direct Javascript Recursion

Direct call recursion is simply a function that calls itself. Here's an example:

function doSomething(param) {
  if (param < 0) {
    return -1;
  } else {
    console.log(param);
    doSomething(param - 1);
  }
}

The thing to avoid at all costs is the common pitfall of an infinite loop. There must always be an end point, a terminating condition or a stopper of the loop. Be sure this critical condition is always encountered otherwise the function will call itself forever or until really bad stuff happens like running out of memory or a computer crash. Just don't go there. One basic brake condition involves counting the number of iterations and if the number exceeds a value that should never naturally occur, force a break in the loop.

Indirect Javascript Recursion

Usually this is a case where Function A calls Function B, then Function B calls Function A. It's still recursive but there is one or more function layer in between.

A slight slant to that is when we purposely create a asynchronous call to the recursive function, such as using a setTimeout function. This is designed to purposely let the processor handle the event loop again so not locking up the thread and preventing other events being handled.

function doSomething(param) {
  if (param < 0) {
    return -1;
  } else {
    console.log(param);
    setTimeout(() => doSomething(param - 1), 1);
  }
}

If your function is likely to iterate many times or may be time consuming then you should consider indirect recursion. If you are programming Javascript for a web page then blocking the event loop would lead to a non-responsive or laggy user experience as the code runs.

Conclusion

In summary, recursive functions are a great solution and can solve a number of problems in an elegant manner, such as sorting or mathematical induction. Use indirect recursion if you need to yield back to the processor and avoid scenarios where your code could get stuck in an infinite loop, or at least code against this.