A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/how-to-understand-recursion-in-javascript/ below:

Recursion Guide in JavaScript - GeeksforGeeks

Recursion Guide in JavaScript

Last Updated : 23 Jul, 2025

Recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, as it can call itself during its execution. Recursion is often used to solve problems that can be broken down into smaller, similar subproblems.

Syntax: JavaScript
function recursiveFunction(parameters) {
  // Base case: stopping condition
  if (baseCase) {
    return baseCaseValue;
  }

  // Recursive case: function calls itself
  return recursiveFunction(modifiedParameters);
}
Key Components:
Example : Factorial of a Number JavaScript
function factorial(n) {
  // Base case: if n is 0 or 1, return 1
  if (n === 0 || n === 1) {
    return 1;
  }

  // Recursive case: n! = n * (n-1)!
  return n * factorial(n - 1);
}

console.log(factorial(5)); // Output: 120
Why Use Recursion?

Recursion is particularly useful for solving problems that can be divided into smaller, identical problems. Some common use cases include:

Example 1: Fibonacci Sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones (e.g., 0, 1, 1, 2, 3, 5, 8, ...).

JavaScript
function fibonacci(n) {
  // Base case: return n if n is 0 or 1
  if (n === 0 || n === 1) {
    return n;
  }
  // Recursive case: sum of the two preceding numbers
  return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6)); // Output: 8
Application of Recursion Tail Recursion

Tail recursion is a special form of recursion where the recursive call is the last operation in the function. This means that the function doesn't perform any additional computation after the recursive call returns. Tail recursion is important because it can be optimized by the compiler or interpreter to avoid growing the call stack, making it more memory-efficient.

Key Characteristics of Tail Recursion
When to Use Tail Recursion

Example: Factorial with Tail Recursion JavaScript
function factorial(n, accumulator = 1) {
  // Base case: 
  if (n === 0 || n === 1) {
    return accumulator;
  }
  // Tail-recursive call: 
  return factorial(n - 1, n * accumulator);
}

console.log(factorial(5)); // Output: 120

Easy Problems on Recursion in JS Medium Problems on Recursion in JS Hard Problems on Recursion in JS
Recursion Introduction in JavaScript

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4