Javascript is a really great language when it comes to flexibility. It is possible to pass code to a function the way you can do with Ruby, albeit a bit more verbose. This is made possible by the fact that javascript allows you to pass a function as one of the parameters of a function.
I’ll demonstrate this by adding a function to Javscript’s arrays which functions like Ruby’s each method. First off let’s create an array that we will play with.
likes = ['ruby', 'javascript', 'ubuntu', 'open source code']
That line is valid in both ruby and javascript. If you are using Firefox, you can execute that code on this page using the Firebug console.
Now let’s extend the Array object by adding a each function.
Array.prototype.each = function(yield) { for(i=0;i<this.length;i++) { yield(this[i]) } }
That code should be more or less self-explanatory. Note that I chose to use yield as the parameter since it feels distinctly Ruby-ish. Now we can use that each function this way:
likes.each(function(item) { alert("I like " + item); });
That is essentially equal to this Ruby code:
likes.each do |item| puts "I like " + item end
Isn’t it amazing how similar the two versions are structurally?
Tags: javascript, ruby