Reputation: 5844
A normal self-invoking function looks like this:
(function () {
// Something.
})();
However, can a function somehow invoke itself in a recursive manner like this:
(function f(i, num) {
if (num > 0) {
console.log(i);
f(i + 1, num - 1);
}
})(0, 2);
but still remain anonymous?
Can an ES6 arrow function invoke itself?
(a => {
// Somehow invoke itself.
})();
Upvotes: 3
Views: 2411
Reputation: 21
Here's a standard abstraction of recursive function definition:
const Y = (r=> r(r))(r=> F=> x=> F(r(r)(F))(x));
Here are a couple of examples of using it:
Y(fac=> n=> n<1 ? 1 : n*fac(n-1))
(5)
// should evaluate to 120
Y(sum=> xs=> xs.length >0 ? xs[0]+sum(xs.slice(1)) : 0)
([30,2,1,4])
// should evaluate to 37
Upvotes: 1
Reputation: 3634
To answer your first question, yes you can have a function invoke itself in the manner you described. In fact, the exact code snippet you gave runs fine. Also the this post
In answer to your ES6 question, no you cannot call an arrow function recursively (at least not in the same way, or any way I've found). The arrow function is shorthand for anonymous function syntax, and is therefore, by definition, anonymous. In order to have a named function you must create it with the function
keyword
Upvotes: 0
Reputation: 11
If you run a cut-down version of your example, you get this:
(function f(n) {
console.log(n);
if (n) {
f(false);
}
})(true);
Running this:
true
false
But then if you try to call it outside of that scope, like:
f();
You get
Uncaught ReferenceError: f is not defined
Seems to answer at least part of the question.
Upvotes: 1
Reputation: 943537
However, can a function somehow invoke itself in a recursive manner like this
Yes. Exactly like that.
but still remain anonymous
No. You have to have a reference to a function in order to invoke it. The only way to get a reference to an IIFE is to give it a name.
The matching variable with that name is, however, only available within the scope inside that function.
Can an ES6 arrow function invoke itself?
Not unless you get a reference to it, which you can't do with an IIFE arrow function.
Upvotes: 6