Skip to content

40 Recursion

Biswajit Sundara edited this page Aug 18, 2023 · 1 revision

Recursion is a programming technique in which a function calls itself repeatedly until a certain condition is met.

  • This is useful in handling repetitive calculations or processing.
  • Recursion is useful when processing data structures such as linked lists and trees.

1. Simple Example (Fibonacci Series)

function factorial(n) {
    if (n === 1) {
      return 1;
    }
    return n * factorial(n - 1);
  }
  
console.log(factorial(3));

We can refactor the code as below.

function factorial(n) {
  return n === 1 ? 1 : n * factorial(n - 1);
}
console.log(factorial(3));

2. Simple Example (Power of)

function powerOf(x,n) {
  return n === 1 ? x : x * powerOf(x,n - 1);
}
console.log(powerOf(5,2));

3. Complex Example

  • Let's say on social media data we are parsing friends list
  • I have friends -> they have their own friend list, and some might not have also
  • So here we are doing repetitive processing, it's related to structure and we don't know the exact count of iterations
  • So recursion is preferred over loops.
const myself = {
  name: "Biswajit",
  friends: [
    {
      name: "Mark",
      friends: [
        {
          name: "Steve",
          friends: [
            {
              name: "Bob",
            },
            {
              name: "Harry",
            },
          ],
        },
      ],
    },
    {
      name: "Jeane",
    },
  ],
};

function getFriendNames(person) {
  const collectedNames = [];
  if (!person.friends) {
    return [];
  }
  for (const friend of person.friends) {
    collectedNames.push(friend.name);
    collectedNames.push(...getFriendNames(friend));
  }
  return collectedNames;
}

console.log(getFriendNames(myself));

Clone this wiki locally