From the for loop to the generator in JavaScript
I recently spent some time writing JavaScript code and do reviews of JavaScript features. JavaScript has some nice language features that make it easy to write short and readable code. (On the other hand it is also quite easy to write horrible code with it.) In this article I try to show you how you can refactor your code to something more readable.
We may start with this non-fictional example:
/**
* Returns array of uids of selected items
*/
getSelected:function() {
var returnArray = new Array();
var modelFriendListItems = this.modelFriendListItems.getSelected();
for (var index = 0 ; index < modelFriendListItems.length ; ++index) {
if(!modelFriendListItems[index].isFacebookUser)
returnArray.push(modelFriendListItems[index].id);
}
return returnArray;
},
It’s just one function out of a class that does quite something typical. This function goes over a list of items (iterate) and builds an array out of some of this items (filter). A friend of mine does some ruby coding and in ruby this would look something like this:
this.modelFriendListItems.getSelected().select{|item| !item.isFacebookUser}.collect {|item| item[:id]}
This is quite short and still yet readable. In JavaScript you can go as well in the direction of more functional programming. So let us refactor the JavaScript example above over some iterations. The following examples use prototype.js because this framework extends the JavaScript array with some fancy functions.
(more…)
