0

I understand that in Javascript a function can return another function and it can be called immediately. But I don't understand the reason to do this. Can someone please explain the reason and benefit why you might want to do this in your code? Also, is the function that returns 'hello' considered a closure?

function a () {
return function () {
    console.log('hello');
  }
}

//then calling the function
a()(); 
user1142130
  • 1,617
  • 3
  • 20
  • 34
  • possible duplicate of [What is a practical use for a closure in JavaScript?](http://stackoverflow.com/questions/2728278/what-is-a-practical-use-for-a-closure-in-javascript) – keenthinker Aug 09 '15 at 17:12

1 Answers1

3

Can someone please explain the reason and benefit why you might want to do this in your code?

There's no reason to do it when you'll always do it whenever calling the function (a in your case). The reason in the general case is that the author of a is allowing for the possibility you may not want to call the resulting function right away. So the a()(); case is just a special case of the general case of

var f = a();
// later...
f();

Also, is the function that returns 'hello' considered a closure?

Yes, technically, although in your example it doesn't have anything special to close over that a doesn't already close over, since there are no arguments to a or variables within a.

More (on my anemic blog): Closures are not complicated

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875