Tip - Avoiding Unnecessary Closures When Looping

When using Prototype's Enumerable methods that expect a function as their argument, it's very easy to add an extra unnecessary closure. It's easy to make the mistake, but also easy to avoid.

For example, say you want to randomize an array of values. A simple way to perform such a feat would be using the handy sortBy function:

var items = [1,2,3,4];
items = items.sortBy(function(item){
  return Math.random();
//items is now something like "2,3,1,4", or whatever.

This code is not optimal, however. In addition to adding a bunch of extra code (which, as we all know, will lead inevitably to more work mantaining it), the extra "function(item)…" closure is not needed. Since sortBy expects a function, and Math.random IS a function, the above code is equivalent to:

var items = [1,2,3,4];
items = items.sortBy(Math.random);

By passing the function reference for "Math.random" in this way, we avoid "items.length" (in this case 4, since we have 4 items) extra function calls, and reduce the code complexity significantly.

As an added note, it's nice and easy to add this method to your array methods as a built-in function, like so:

Array.prototype.randomize = function(){
  return this.sortBy(Math.random);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License