4

Since closures and the ability to call a function later with its closed over variables seems to be a big plus with javascript's capabilities, I'm finding myself constantly using the following construct:

var func;
func = function (args) {return function (moreArgs) {
    Do something;
};};

Is this normal javascript programing or is there a problem/trap with implementing all functions this way? I'm not seeing any disadvantages and this pattern always sets a function up with the potential benefits of a closure... with the ability to pass it around and execute it later.

When the closure is needed, it can be called twice like this:

func()(parms);

... but that's a rare occurance.

This seems to work fine in every situation. Is this the way functions should be set up in Javascript or is this overusing closures? There doesn't seem to be any material disadvantages to this approach.

ciso
  • 2,887
  • 6
  • 33
  • 58
  • 1
    Not sure I'd write *every* function like that, but modular patterns that put functions with similar concerns into one closure so they effectively have their own set of pseudo–global variables are very common. – RobG May 26 '15 at 03:19
  • 5
    The whole idea is called "currying" – zerkms May 26 '15 at 03:21

2 Answers2

3

When I don't need the closure, I just call it twice like this:

func()(parms);

There's your reason not to do this. It's unnecessary most of the time, and generally unconventional. Stick to the basics so your code isn't a bizarre island unto itself. Not that the pattern is never appropriate - it is - but definitely don't do it all the time for no reason.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • 1
    Plus every closure consumes some memory so no point in doing that if there's no need or benefit in doing so. – jfriend00 May 26 '15 at 04:03
3

What you are trying to do, is sort of called function currying. But again there is the words 'sort of'. This guides how to do it correctly, in case you are interested.

Try to use closure exactly when you need it. Because closure can cause serious memory leaks if you dont know what you are doing. And google optimization says

Creating a closure is significantly slower than creating an inner function without a closure, and much slower than reusing a static function

years_of_no_light
  • 938
  • 1
  • 10
  • 24
  • In case the above link on how to perform curry is broken, here is another one http://www.sitepoint.com/currying-in-functional-javascript/. – years_of_no_light Mar 27 '16 at 07:30