Blog

Recursion from Four Semesters of Computer Science in 5 Hours by Brian Holt
Posted on August 5, 2020 in Algorithms, JavaScript by Matt Jennings

Recursive Function Definition

A recursive function is a function that calls itself until it doesn’t. And this technique is called recursion. 

Stack overflow is when a function calls itself two many times for the memory available in a computer, or a function calls itself infinite times. Below is an example of stack overflow:

// In Google Chrome the error below is produced:
// Uncaught RangeError: Maximum call stack size exceeded
function foo() {
    return foo();
}
foo();

Recursion example with a base case to prevent stack overflow:

function basicRecursion(max, current) {
  // Base case which prevents stack overflow
  // and if current is greater then
  // function stops
  if (current > max) return;
  console.log(current);
  basicRecursion(max, current + 1);
}

// Console logs off 1, 2, 3, 4, 5
basicRecursion(5,1);

Factor recursion example:

function factorial(n) {
  if(n < 2) return 1;
  return n * factorial(n - 1);
}

console.log(factorial(5));

/*
5 * factorial(5 - 1);
4 * factorial(4 - 1);
3 * factor(3 - 1);
2 * 1;
5 * 4 * 3 * 2 * 1;
*/

Leave a Reply

To Top ↑