So, a few days ago I finally decided to give JavaScript a proper chance and as it turns out; All those people who’s been blabbering on about how JavaScript actually is a very powerful language where right all along!
You see, just like Ruby, JavaScript is extremely flexible, for instance, here’s how you would typically loop over an array:
[cc lang="javascript"]
var myArray = [1, 2, 3, 4, 5];
for (var i=0; i < myArray.length; i++) {
alert(myArray[i]);
};
[/cc]
However, in Ruby land we’ve grown to know and love the [].each { |elem| … } way of looping, JavaScript doesn’t have that but fortunately adding it yourself is trivial:
[cc lang="javascript"]
// Extend the Array object with an each function
Array.prototype.each = function(fn) {
// Loop through each element in this (which will be the
// array instance we call each on)
for (var i=0; i < this.length; i++) {
// Call the callback function with it’s context
// set to the current array element
fn.call(this[i]);
};
};
// With our new each function in place we can now iterate
// over an array like this
[1, 2, 3, 4, 5].each(function() {
alert(this);
});
[/cc]
Now, even though this is a very simple example, it does give you an idea of just how powerful of a language it really is, and while it’s not as pretty to look at as ruby, thereof the unfortunate disguise, dismissing JavaScript as a toy language just isn’t viable any more.
Tagged with JavaScript, Ruby. Written by: Patrik Hedman
