JavaScript, a quite capable ruby in an unfortunate disguise
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:
1 2 3 4 | var myArray = [1, 2, 3, 4, 5]; for (var i=0; i < myArray.length; i++) { alert(myArray[i]); }; |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // 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); }); |
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.
