There are many questions about recursion with function expressions. And there are two ways to do it: One is using named function expression and second is using arguments.callee. But at this time arguments.callee is deprecated.
The question is what about recursion with function declaration. How can we remove arguments.callee from this example and not be depended on the function name.
function fib(n){
return n < 3 ? 1 : arguments.callee(n - 1) + arguments.callee(n - 2);
}
For function declarations there is no built-in mechanism to have safe self-reference. If the function is renamed, then using the name inside the body would be lead to an error
And
arguments.calleethrows an error in strict mode:However, any recursive function can be made name-agnostic with the Y combinator (also called fixed-point combinator). Put simply it allows for a function to call itself without needing to have a formal name. In some languages it might not be possible for a function to refer to itself. In others, like JavaScript, it can. However, you can still leverage the Y/fixed-point combinator to avoid having to do that.
The function would need to be transformed to take one parameter which will be itself and then returns a function that uses said parameter for recursive calls. It is a bit more obvious if shown as an arrow function:
While using function declarations it will be
The implementation of the Y combinator itself is
(from "Common combinators in JavaScript" by Avaq on GitHub)
And the usage is: