Coffeescript: for key, value in array

I just found something really disappointing with Coffeescript.


obj = {a:1, b:2, c:3}
arr = [3,4,5]

# Prints: 3-0, 4-1, 5-2
for v,k in arr
    console.log v+"-"+k

# Prints: 1-a, 2-b, 3-c
for k,v of obj
    console.log v+"-"+k

Notice how I had to invert the key and value in the array loop? It’s annoying. It’s inconsistent. It’s amateurish.

I understand that 98% of the time, for … in is used without the need for a key reference, but sometimes you need to keep track of the loop counter and the coffeescript.org documentation is really not helpful in that regard.

I could make my own loop counter, but it’s even uglier than memorizing this gotcha, so I’m going to stick with the gotcha..

My impressions after a week of CoffeeScript

Until a few days ago, I was a hardcore pure JavaScript believer.
I didn’t want to hear anything about Dart, TypeScript, LiveScript, CoffeeScript, IcedCoffeeScript and all the other compile-to-JS languages out there. To me, they were only an additional layer of stuff that could go wrong. I still think they’re all too focused on solving a non-issue with JS, namely the prototypal Object system. I absolutely love the approach used by Javascript when it comes to OOP because it takes the best functional-style features of JS and creates an elegant way of managing objects during runtime.

I’ve been following the development of ECMAScript 6 for many months, and I’m excited by all the new features, like list comprehensions, splats, array destructuring, syntactic sugar for map/reduce/filter/etc and many others. I’m sure you can see where I’m going with this. I knew CoffeeScript provided all that, but to me it was just a layer of features that are about to land in V8 any second now, so why bother learning it? Well, for one, the dense syntax is great. It can be really confusing at first. Take this snippet, for example. It prints the numbers from 1 to 5, waiting 1 second every time.

for (var i=1;i<=5;i++){
    (function(i){
        setTimeout(function(){
            console.log(i);
        }, i*1000);
    })(i);
}

Continue reading