Skip to main content

Command Palette

Search for a command to run...

Recursion in JavaScript

Updated
2 min read
Recursion in JavaScript
A

Experienced mobile app developer who has a track record of success creating apps that are both well-received and commercially viable. Skilled with working as a team and incorporating input into projects. Ability to always look for ways to improve upon an already existing app to keep people downloading it and enjoying it. Strong eye for detail and tenacity to never quit on something until it is absolutely perfect.

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();

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

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

recurse();

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

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

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

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

More from this blog

Anas Nabil's Blog

16 posts