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 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..

Leave a Reply