JavaScript Recursive Function

Total
1
Shares

Today, we will look at one of the most used concepts of JavaScript Recursion technique to develop a JavaScript Recursive Function. Recursion means to reoccur/ happen again. The same concept is applied in JavaScript to carry out repetitive tasks.

Introduction to the JavaScript recursive functions

Let us start by understanding recursion.

Recursion is a programming technique using function or algorithm that calls itself one or more times until a specified condition is met.

Recursion performs computations by creating a function that calls itself until it accomplishes the desired task/reaches the desired output. A Recursive function calls itself until the condition is false and the recursion ends.

Let us look at the syntax of the recursive function.

function recurseFunc() {
    // ...
    recurseFunc();

    // ...

}

It is written just like any other functions the only difference is that it calls itself from within the function body.

A recursive function must have a condition to halt the execution. If an exit condition is not present, the code will loop indefinitely.

Once it meets the exit requirement, the function stops calling itself. It is also known as the Base condition.

To control indefinite calling, we create conditional branches. One branch leads to recursion. The other does not.

function recurseFunc() {
    if (condition) {
        // if condition is met stop the execution
        //...
    } else {
        recurseFunc();
    }
}

JavaScript recursive function examples

1) A simple JavaScript recursive function example

Let us understand this with an simple example.

function sumNum(num){
    if(num > 5){
        return;
    }
    console.log(num);
    sumNum(num + 1);
}

Now let us suppose that we call the function with the value 0.

sumNum(0);
Recursive callnum output
100
211
322
433
544

If we omit the exit condition, let us see how it behaves.

function sumNum(num){
  console.log(num);
    sumNum(num + 1);
}
Recursive callnum output
100
211
400300300
544
700060006000…………..So on

The numbers will never end as there is no exit condition so it goes into an infinite loop.

2) JavaScript Program to Find Factorial of Number Using Recursion

In this example, you will learn to write a JavaScript program to find the factorial of a number using recursion function.

The factorial of a number is the multiplication of every number below it till it reaches 1

For example,

factorial of 5 is equal to 5 * 4 * 3 * 2 * 1 = 120.

// find the factorial of a number
function fact(num) {

    // if number is 0
    if (num === 0) {
        return 1;
    }

    // if number is positive
    else {
        return num * fact(num - 1);
    }
}

const val = 5;

// if val is non-negative
if (val > 0) {
    let resultFact = factorial(val);
    console.log(`The factorial of ${val} is ${resultFact}`);
}

Output

The factorial of 5 is 120

The above JavaScript function calculates the factorial of a number. It multiplies the number with one less than the number itself. It does so until it reaches 0.

Why don’t we use a loop instead of Recursive functions?

Any situation that we can solve using a recursive function can also be solved using an alternative looping solution. For example recursion can be written as.

let temp = 1;
for (let x = 3; x >= 1; x--) {
    temp = temp * x;
    console.log(temp);
}

Recursion is preferred as the loop demands you to know how many times we will repeat the execution beforehand.

A recursive function executes a piece of code without comprehending how many times we need to replicate it.

Recursion functions are more suitable method of coding when compared to loops. In most cases, the time complexity of a recursive answer is more satisfactory than the loop one.

Conclusion

JavaScript Recursive Function is a programming technique using function or algorithm that calls itself one or more times until a specified condition is met. In case of recursion the code size will be smaller.

Loops on the other hand demands you to know the how many times it needs to repeat the execution before hand. The code size could go larger in case of loop when the complexity arrives.

Recursion is better for a complex problem whereas for simpler pieces of code use a loop.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Get notified on the latest articles

You May Also Like
JavaScript String endsWith()

JavaScript String endsWith()

Table of Contents Hide endsWith() SyntaxendsWith() ParametersendsWith() Return ValueJavaScript String endsWith() examplesJavaScript endsWith() example with length parameter In JavaScript, the endsWith() method determines whether the given string ends with a…
View Post