Iterators in JavaScript - look to Ruby

December 06, 2005

...

Dynamic languages are gaining popularity these days, Ruby is particularly hot. JavaScript is also a dynamic language, however somewhat more verbose. This means that we can borrow a lot of tricks from other dynamic languages. Something that I like very much in the Ruby language are blocks and iterators. Consider the following Ruby code:

5.times { print 'Hi! ' }

This very simple code snippet shows an iterator times on the 5 object that iterates over the block print 'Hi! '. Now, in JavaScript we can do exactly the same. It only requires a little more code, as numbers are primitives in JavaScript, and not objects like in Ruby. However, we can use the Number object instead:

Number.prototype.times = function(lambda) {

  for (i = 0; i < this.valueOf(); i++) {  
    lambda();  
  }  
}
 
new Number(5).times(function() {alert("Hi!");});

Well, that was fun, but not very useful, you may think. But wait. Let’s look at one more example. Consider the examples with arrays i blogged about yesterday. Instead of creating a map function, let’s make an iterator on the Array object instead. Like so:

Array.prototype.foreach = function(lambda) {  
  for (i = 0; i < this.length; i++) {  
    var x = lambda(this[i]);  
    if (null != x ) {  
      this[i] = x;  
    }  
  }  
  return this;  
}
 
var y = [1,2,3,4,5].foreach(function (x) { return x+1; });

Now, we created an iterator on the Array prototype object that applies a certain anonymous unary function to each element in the array. If the function returns a value, the new value is stored in the element’s original position in the array. At last the array itself is returned.

Once again, we are able to write much more compact code by using higher-order functions (functions that take functions as arguments).


Profile picture

Written by Vidar Kongsli who is a software professional living in Oslo, Norway. Works as a consultant, system architect and developer at Bredvid. You should follow him on Twitter