#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 49 of 50medium

How does Recursion work in JavaScript?

Understanding recursive functions.

What You'll Learn

  • Recursive function structure
  • Base case importance
  • Common examples

What is Recursion?

A function that calls itself to solve smaller instances of the same problem.

code.jsJavaScript
function countdown(n) {
  if (n <= 0) {           // Base case
    console.log('Done!');
    return;
  }
  console.log(n);
  countdown(n - 1);       // Recursive call
}

countdown(3); // 3, 2, 1, Done!

Classic Examples

code.jsJavaScript
// Factorial: n! = n * (n-1)!
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
factorial(5); // 120

// Fibonacci
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}
fibonacci(6); // 8

// Sum of array
function sum(arr) {
  if (arr.length === 0) return 0;
  return arr[0] + sum(arr.slice(1));
}
sum([1, 2, 3, 4]); // 10

Deep Operations

code.jsJavaScript
// Flatten nested array
function flatten(arr) {
  return arr.reduce((flat, item) => {
    return flat.concat(
      Array.isArray(item) ? flatten(item) : item
    );
  }, []);
}
flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4]

// Deep clone
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (Array.isArray(obj)) return obj.map(deepClone);
  return Object.fromEntries(
    Object.entries(obj).map(([k, v]) => [k, deepClone(v)])
  );
}

Stack Overflow Prevention

code.jsJavaScript
// Tail recursion (optimization in some engines)
function factorialTail(n, acc = 1) {
  if (n <= 1) return acc;
  return factorialTail(n - 1, n * acc);
}

// Or use iteration for large inputs