DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 970,177 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Recursion in JavaScript
Anas Nabil
Anas Nabil

Posted on • Updated on

Recursion in JavaScript

What is Recursion?

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


Syntax

const recurse = () => {
    recurse();
}

recurse();
Enter fullscreen mode Exit fullscreen mode

This recursive function will keep calling itself forever, So it needs a little more touches

const recurse = () => {
  if (condition) {
    recurse();
  }
  // stop calling recurse()
};

recurse();
Enter fullscreen mode Exit fullscreen mode

This function will continue calling itself as it meets the condition, else will stop running.


Examples

1- Simple Example

const countDown = (start, end) => {
  console.log(start);
  if (start > end) {
    countDown(start - 1, end);
  }
};

countDown(19, 7); // 19 18 17 16
Enter fullscreen mode Exit fullscreen mode

Behind the scenes

  • countDown(19, 7) prints 19 and calls countDown(18, 7)
  • countDown(18, 7) prints 18 and calls countDown(17, 7)
  • countDown (17, 7) prints 17 and calls countDown(16, 7)
  • countDown (16, 7) prints 16 and stop running.

2- Factorial

  • 0! = 1
  • 1! = 1
  • 2! = 2 * 1
  • 3! = 3 * 2 * 1
  • 4! = 4 * 3 * 2 * 1
  • 5! = 5 * 4 * 3 * 2 * 1
const factorial = (num) => (num < 0 ? -1 : num === 0 ? 1 : num * factorial(num - 1));

console.log(factorial(5)); // 120
Enter fullscreen mode Exit fullscreen mode

Behind the scenes

  • factorial(5) = 5 * factorial(4)
  • factorial(4) = 4 * factorial(3)
  • factorial(3) = 3 * factorial(2)
  • factorial(2) = 2 * factorial(1)
  • factorial(1) = 1 * factorial(0)
  • factorial(0) = 1

3- Fibonacci

A fibonacci sequence is written as:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...

The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms. Hence, the nth term is the sum of (n-1)th term and (n-2)th term.

Here's a code that returns the fibonacci value at a given index using recursion

const fibonacci = (n) => (n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2));

console.log(fibonacci(5)); // 5
Enter fullscreen mode Exit fullscreen mode

Behind the scenes

  • fibonacci(5) = fibonacci(4) + fibonacci(3)
  • fibonacci(4) = fibonacci(3) + fibonacci(2)
  • fibonacci(3) = fibonacci(2) + fibonacci(1)
  • fibonacci(2) = fibonacci(1) + fibonacci(0)
  • fibonacci(1) = 1
  • fibonacci(0) = 0

Oldest comments (0)

You’ve already scrolled down this far, why not join our community of 900k+ developers all learning together?