JavaScript recursion

Understand the basics of recursion in JavaScript

A function can call itself.

This is what recursion means. It allows us to solve problems in a concise way.

To do this, you need a named function expression, in other words, this is:

function doSomething() {

}

So we can calldoSomething()insidedoSomething().

The simplest example we can make is calculating a factorial of a number. This is the number that we get by multiplying the number for (number - 1), (number - 2), and so on until we reach the number 1.

The factorial of 4 is (4 * (4-1) * (4-2) * (4-3)) = 4 * 3 * 2 * 1, which is 24.

We can create a recursive function to automatically calculate it:

function factorial(n) {
  return n >= 1 ? n * factorial(n - 1) : 1
}

factorial(1) //1 factorial(2) //2 factorial(3) //6 factorial(4) //24

If we want, we can also use the arrow function:

const factorial = (n) => {
  return n >= 1 ? n * factorial(n - 1) : 1
}

factorial(1) //1 factorial(2) //2 factorial(3) //6 factorial(4) //24

Now it's time to talkCall stack.

Suppose we made a mistake instead of calculating the factorial as

const factorial = (n) => {
  return n >= 1 ? n * factorial(n - 1) : 1
}

We do this:

const factorial = (n) => {
  return n >= 1 ? n * factorial(n) : 1
}

As you can see, we are callingfactorial(n)Ads are unlimited. There is no end, because we forgot to lower it every time we call.

If you run this code, the following error will appear:

RangeError: Maximum call stack size exceeded

Every time a function is invoked, JavaScript needs to remember the current context before switching to the new one, so it puts that context on the call stack. As soon as the function returns, JavaScript goes to the call stack and picks the last element that was added, and resumes its execution.

Maximum call stack size exceeded means that too many elements were put on the stack, and your program crashed.


More js tutorials: