73
for (i = 0; i < 10; i++) {

    doStuff();

}

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

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
Shamoon
  • 41,293
  • 91
  • 306
  • 570

3 Answers3

115
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()   
jontro
  • 10,241
  • 6
  • 46
  • 71
  • 27
    Right, or to translate it literally, `for i in [0...10]`. Two dots (`..`) means "up to and including," while three dots (`...`) means "up to but not including." It's a Ruby-ism. – Trevor Burnham Sep 07 '11 at 18:09
  • The range operators originate from [Perl](http://perldoc.perl.org/perlop.html) which heavily influenced Ruby. Not sure if Perl invented them or inherited from another ancient language. – matyr Sep 08 '11 at 13:33
  • @JP Well if you introduce a variable in the loop the code will behave differently. For example it will determine runtime which way the counter should go. 0 .. 0 should execute once. 0 .. -1 should execute twice. – jontro Oct 24 '11 at 11:14
  • @Bengt exactly. I thought it was an important to modify the answer so that would be internet searchers don't get confused. AFAIR, the CoffeeScript docs aren't clear on this. I got burned by it, I don't want others. I think my additional examples spell this out for people. – JP Richardson Oct 24 '11 at 20:31
19

The marked answer is functionaly correct but the generated code doesn't match the original javascript.
The right way (read, the one closest to the following javascript)

for (i = 0; i < 10; i++) {
  doStuff();
}

is doStuff() for i in [0..someCount] by 1 Note the by 1 on the for loop.

Now this code, still creates an extra _i variable. If you can't live with it, then use the following:

i=0
while i<=someCount
  doStuff()
  i++
Olivier Refalo
  • 50,287
  • 22
  • 91
  • 122
1

Previous answers work. However, dropping the i generates it better for me:

for [0...10]
  doStuff()

or

doStuff() for [0...10]

The other solutions add an extra iterator variable i for you to use inside of the loop, for example doStuff(i), but from http://coffeescript.org/v1/#loops:

If you don’t need the current iteration value you may omit it:

browser.closeCurrentTab() for [0...count]

In detail, the translation of for i in [0...10] is for (i = j = 0; j < 10; i = ++j), whereas the translation of for [0...10] is for (i = 0; i < 10; i++).

Note the discussion in other comments about 2-dots versus 3-dots ([0..9] vs. [0...10]).

stevo
  • 468
  • 5
  • 10