Function that returns another function by returning itself

Asked

Viewed 194 times

0

First of all, I’m asking this out of sheer curiosity, there’s no real application where that would be useful (or has it? I don’t know).

I know that it is possible to make a function return another function, and that the returned function can be a parameter, i.e..

function a(b) {
    return b();
}

Then, if I pass a function within the "a" function, it returns the function that was used as a parameter after its execution. Exemplifying again:

function foo() {
    return 'bar';
}

console.log(a(foo)); // printa 'bar'

So far, so good. However, and when I try to invoke the function itself a within itself?

a(a); // erro

I tried, and the answer is a mistake stating b is not a function.

I wanted to understand how/why this happens. In my head it should enter an infinite processing cycle, and lock, or something like that. I missed something?

  • What you intend to do is called recursion. There are dozens of questions on the subject and one of them will help you is: https://answall.com/questions/202514/fun%C3%A7%C3%B5es-recursivas-em-javascript

  • 1

    the name "a" is generating confusion, if associating to another variable should work: var x = a;
console.log(a(x));

  • Theotonio, I understand the concept of recursion, but in this case, recursion invokes a function declared within itself. In this case, the function would invoke another eternal function to the scope of the original function. No different?

1 answer

3


You missed a detail yes. When you call the function a it is necessary to pass a parameter, which does not happen here:

a(a); // o a de dentro não recebe o parâmetro

So when a executes return b(); - execution of the internal a, no parameter - you receive the error because parameter b is not defined, since this was not passed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.