Recursive Anonymous Functions in JavaScript

It is possible to create recursive anonymous functions in JavaScript.

Usually we need a name for a function to recursively refer to itself, but since anonymous functions have no name, JavaScript provides arguments.callee as a way to refer to the function that called the function we are currently executing!

First, here is a regular factorial function using its name to refer to itself:

var fact = function(n) {
  if (n === 0) {
    return 1;
  } else {
    return n * (fact(n - 1));
  }
}

We can replace that name reference with arguments.callee:

var fact = function(n) {
  if (n === 0) {
    return 1;
  } else {
    return n * (arguments.callee(n - 1));
  }
}

In this way, we can use recursive functions without ever giving them a name!

In the following code we print out the factorial of 5 computed with an anonymous function, never giving it a name:

console.log(
  (function(n) {
    if (n === 0) {
      return 1;
    } else {
      return n * (arguments.callee(n - 1));
    }
  })(5)
);

See these important notes about this feature of JavaScript:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee