Created
March 21, 2023 10:12
-
-
Save imtrinity94/05fae0c30090d000316d437a087ed5a2 to your computer and use it in GitHub Desktop.
Using arguments.callee in an anonymous recursive function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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