jashkenas/coffee-script — Issue #1814: For loops don't work consistently for strings
Author: joewhite
Created: 2011-10-30 02:19:28+00:00
State: open

I found myself needing to loop over the characters in a string, so I tried a `for` loop:

for char, index in line:
# ...

It turns out this isn't actually supported, but I couldn't tell because it worked just fine. CoffeeScript happily compiled my loop to:

for (index = 0, _len2 = line.length; index < _len2; index++) {
char = line[index];
// ...

But as I later learned, JavaScript strings haven't always supported indexers -- and sometimes still don't; if you run this code in IE, and your page does not have an HTML5 doctype declaration, then `line[x]` will return `undefined`. (If you do have the HTML5 doctype, then this code works just fine in IE. Go figure.)

For reference, it looks like the correct way to loop over the characters in a string (which, unfortunately, requires remembering the difference between those wretched `..` and `...` operators) is:

for index in [0...line.length]:
char = line.charAt index
# ...

It would be nice if CoffeeScript didn't make it so easy to generate code that looks fine in modern browsers but that will fail in older browsers. Perhaps the documentation should clearly and loudly call out the fact that `for` isn't meant for use with strings (though that would be a pity; the "correct" alternative is a lot uglier). Perhaps the compiler should emit guard code around `for` loops to throw a "hey, this isn't supported" error if the thing being iterated over is a string. Perhaps the compiler should emit code that works correctly even if you do pass in a string. Other ideas?