insights of coffee script’s IN and OF loops
We make heavy use of coffee script and usually it can keep its promise to make our coding live a little bit easier. Usually … We knew both the “in” and “of” loop but we never thought about the underlying implementation and the impact IE could have. So I’ll share our two main WTFs so you won’t have to repeat them:
Let’s first have a look how “in” and “of” compiles into JS:
for key, value of arr
alert key
alert value
in JS it looks like this:
var key, value, _len; for (key in arr) {
value = arr[key];
alert(key);
alert(value);
}
So “of” becomes” “in” …
for value, key in arr
alert key
alert value
—>
for (key = 0, _len = arr.length; key < _len; key++) {
value = arr[key];
alert(key);
alert(value);
}
Do you see the difference? The order of “value” and “key” (key,value vs. value,key) is inverted! WTF?!?! This WILL produce bugs!
The next thing is: You should never use for-in loop on arrays but especially in IE you’ll get into trouble ( http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays ). Hard if you don’t know what will happen behind your coffee script…
So always keep in mind what coffee scripts IN and OF means, that will reduce you WTFs/min