How can I convert a JavaScript for-loop to CoffeeScript?

Shamoon picture Shamoon · Sep 7, 2011 · Viewed 57.5k times · Source
for (i = 0; i < 10; i++) {

    doStuff();

}

That's the JavaScript code that I Want to convert to CoffeeScript.

Answer

jontro picture jontro · Sep 7, 2011
doStuff() for i in [0 .. 9]

This is explained on the introduction page: http://coffeescript.org/#loops

Edit/Update by JP:

The exact translation is:

doStuff() for i in [0...10]

You need to be careful with the ".." vs "...", for example:

count = 0
doStuff() for i in [0..count] #still executes once!

So you think, no problem... I'll just loop until count-1!

count = 0
doStuff() for i in [0..count-1] #executes twice!! '0' and then '-1'

Literal translation of:

for (var i = 0; i < someCount; ++i)
  doStuff()

is

for i in [0...someCount]
  doStuff()