Here are some reasons to avoid making lots of things like map
and filter
be global variables:
Naming conflicts with other code/libraries attempting to do something similar, but incompatible. If all code is using numerous global functions, then the simple definition of a single global function could completely break your app because it would be redefining such a function used for something else somewhere else in the code. This, all by itself, is a reason to use as few globals as possible. In a team project or a project using significant third party libraries, this is impossible to manage and will inevitably lead to lost productivity or, even worse, bad bugs that might not immediately be apparent.
Code modules are less self describing when a symbol is just global. Hmmm, where does the symbol map()
come from. Is this built in? Is it defined locally? Is it defined by some library? It's a lot easier to know where gutils.map()
comes from (from the gutils
module). Large numbers of global anything is just less maintainable than breaking things into well defined modules.
There are numerous advantages to defining functions as methods on the objects on which they operate (such as ES5 .map()
and .filter()
being methods on the Array object rather than as generic globals). Now, it is considered bad practice to add non-standard methods to existing built-in objects (also for naming collision reasons), but adding polyfills that implement standard behavior is encouraged.
See these references for other info:
How and Why to Avoid Globals in Javascript
I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?
Essential Javascript Namespacing Patterns
Javascript Namespaces and Modules
How do I declare a namespace in JavaScript?
As to the topic of performance, it should not be your first concern and will likely not even be a relevant concern in most code. It is much more important to start with a robust, maintainable coding strategy and then optimize only small pieces of code where performance is critical than to sacrifice robustness at the beginning in the name of performance.
In any tight loop where performance is criticial, you can always assign any function to a local variable to slightly improve performance and this will be faster than either a module reference or a global reference (because locals are resolved before globals).
So, if you had gUtils.map()
in a module and you want to maximize performance inside a particular function, you can do this:
function x() {
var map = gUtils.map;
for (var i = 0; i < someBigNumber; i++) {
map(...);
}
}