Since Javascript 1.2 and later there has been a cool and very powerful literal syntax for functions:

var sum = function(x, y) {return x+y}

A couple of weeks ago I found an interesting use of this syntax. Missing Ruby’s wonderful each function, I decided to implement something similar in JS, and, after some experimentation, ended up with this:

function each(a, f) { for(var i=0, l=a.length; i<l; i++) f(a[i]) };

The function syntax comes in handy when you use this each:

each([1, 2, 3, 4, 5], function(e) { alert(e) });

It may not be as satisfying as Ruby’s each, but it’s quite useful.

optional, published, followed

optional, not published
email me new comments to this post
remember my name, blog, and email (forget me!)

antispammer
Textile and some HTML spoken.
Preview