Javascript - Function Function Recursion

Introduction

A recursive function is formed when a function calls itself by name:

function factorial(num){
   if (num <= 1){
       return 1;
    } else {
        return num * factorial(num-1);
    }
}

var anotherFactorial = factorial;
factorial = null;
console.log(anotherFactorial(4));  //error!

Here, the factorial() function is stored in a variable called anotherFactorial.

The factorial variable is then set to null, so only one reference to the original function remains.

When anotherFactorial() is called, it will cause an error, because it will try to execute factorial(), which is no longer a function.

Using arguments.callee can alleviate this problem.

arguments.callee is a pointer to the function being executed and can be used to call the function recursively:

function factorial(num){
       if (num <= 1){
           return 1;
       } else {
           return num * arguments.callee(num-1);
       }
}

It's advisable to always use arguments.callee of the function name whenever you're writing recursive functions.

The value of arguments.callee is not accessible in strict mode.

You can use named function expressions to achieve the same result. For example:

var factorial = (function f(num){
    if (num <= 1){
        return 1;
    } else {
        return num * f(num-1);
    }
});

Here, a named function expression f() is created and assigned to the variable factorial.

The name f remains the same even if the function is assigned to another variable.

This pattern works in both nonstrict mode and strict mode.