Skip to content

Recursive functions in JavaScript

Posted on:May 8, 2023

Table of contents

Open Table of contents

Intro

Recursion is a process of calling itself. A function that calls itself is called a recursive function. A recursive function is a function designed to call itself directly or indirectly. Using recursion, a problem can be solved by returning the value call of the same particular function.

When a function calls itself, that’s called a recursion step. The basis of recursion is function arguments that make the task so simple that the function does not make further calls.

Syntax

function recurse() {
    recurse();
}

recurse();

Examples

Linear sum

function sum(number) {
    if (number === 0) {
        return 0;
    }
    return number + sum(number - 1);
}

sum(5);

Count down

function countDown(start) {
  if (start <= 0) {
    return;
  } else {
    console.log(start);
    countDown(start--);
  }
}

countDown(5);

Factorial of a number

function factorial(number) {
    if (number === 1) {
        return 1;
    }
    return number * factorial(number - 1);
}

factorial(7);

Fibonacci sequence

function sequence(number) {
    function calc(number) {
        if (number <= 1) {
            return number;
        }
        return calc(number - 1) + calc(number - 2);
    }
    let string = '';
    for(let i=1; i<=number; i++) {
        string += `${calc(i)} `;
    }
    console.log(string);
}

sequence(15)

Alternatives

Modern programming languages like JavaScript already have the for and while statements as alternatives to recursive functions. Iterative loops can be more efficient than recursive functions, as they avoid the overhead of function calls. There are also other alternatives such as: memoization, stack-based algorithms and divide-and-conquer algorithms, with recursion, what matters most is the condition that terminates the executive and not the number of times it has to run. But this is not sure for iterators.

Outro

Recursive functions are commonly used in computer science and programming to solve problems that can be broken down into smaller sub-problems.

The base case is an important aspect of recursive functions, as it determines when the recursion should stop. A recursive function must always have at least one base case to make it stop calling itself or it will cause an error.