Recursion in JavaScript

anasnmu

Anas Nabil

Posted on July 25, 2022

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

💖 💪 🙅 🚩
anasnmu
Anas Nabil

Posted on July 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Recursion in JavaScript
javascript Recursion in JavaScript

July 25, 2022

Traversing a Binary Search Tree in JS
javascript Traversing a Binary Search Tree in JS

December 23, 2021

Algorithmic Problem Solving - Step by Step
javascript Algorithmic Problem Solving - Step by Step

November 18, 2021