Skip to content

Instantly share code, notes, and snippets.

@imtrinity94
Created March 21, 2023 10:12
Show Gist options
  • Save imtrinity94/05fae0c30090d000316d437a087ed5a2 to your computer and use it in GitHub Desktop.
Save imtrinity94/05fae0c30090d000316d437a087ed5a2 to your computer and use it in GitHub Desktop.
Using arguments.callee in an anonymous recursive function
/* Using arguments.callee in an anonymous recursive function
A recursive function must be able to refer to itself. Typically, a function refers to itself by its name. However, an anonymous function (which can be created by a function expression or the Function constructor) does not have a name. Therefore if there is no accessible variable referring to it, the only way the function can refer to itself is by arguments.callee.
The following example defines a function, which, in turn, defines and returns a factorial function. This example isn't very practical, and there are nearly no cases where the same result cannot be achieved with named function expressions. */
function create() {
return function (n) {
if (n <= 1) {
return 1;
}
return n * arguments.callee(n - 1);
};
}
const result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment