Sunday, 9 December 2018

Explain different ways to achieve recursion in JavaScript

Recursion is a technique, where the function call itself directly (or) indirectly.

There are three ways to refere a function itself.
a.   the function's name
b.   arguments.callee
c.   an in-scope variable that refers to the function

Using the functions name
HelloWorld.js
function factorial(n){
    if(n <= 1){
        return 1;
    }
    
    return n * factorial(n-1);
}

console.log(`Factorial of 5 is ${factorial(5)}`);

Output
Factorial of 5 is 120

Using arguments.callee
HelloWorld.js
function factorial(n){
    if(n <= 1){
        return 1;
    }
    
    return n * arguments.callee(n-1);
}

console.log(`Factorial of 5 is ${factorial(5)}`);


Using an in-scope variable that refers to the function
HelloWorld.js

var fact = function factorial(n){
    if(n <= 1){
        return 1;
    }
    
    return n * fact(n-1);
}

console.log(`Factorial of 5 is ${factorial(5)}`);



Previous                                                 Next                                                 Home

No comments:

Post a Comment