Recursion Guide in JavaScript (original) (raw)

Last Updated : 14 Feb, 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

Similar Reads

Mathematical









Recursion







Array








Searching






Sorting












Hashing



String







Linked List