2 of 2 added 817 characters in body

You should put it at global scope, for several reasons.

  • Nesting a helper function into the caller increases the length of the caller. Function length is almost always a negative indicator; short functions are easier to understand, to memorize, to debug and to maintain.

  • If the helper function has a sensible name, reading that name is enough without needing to see the definition nearby. If you do need to see the helper definition in order to understand the caller function, then that caller is doing too much, or is working on too many levels of abstraction simultaneously.

  • Having the helper globally available allows other functions to call it if it turns it to be generally useful after all. If the helper isn't available, you're tempted to cut and paste it, or to forget it and reimplement it, poorly, or to make another function longer than it has to be.

  • Nesting the helper function increases the temptation to use variables from the caller's scope without declaration, so that it becomes unclear what the inputs and outputs of the helper are. If a function doesn't clearly state what data it operates on and what effects it has, it is usually a sign of unclear responsibilities. Declaring the helper ass a standalone function forces you to know just what it actually does.


That turned out to be a more controversial question than I thought. To clarify:

In JavaScript, big file-spanning functions often fulfill the role of classes because the language doesn't provide any other scope-limiting mechanism. Certainly helper functions should go inside such quasi-classes, not outside them.

And the point about easier reuse presupposes that if a subroutine does become more widely used, you are willing to move it out of place altogether and put it in appropriate place, e.g. a string utility library or into your global configuration registry. If you don't want to order your code like that, then you might as well nest the subroutine, just like you would do with a normal Method Object in a more "blocky" language.