for (i = 0; i < 10; i++) { doStuff(); }
That's the JavaScript code that I Want to convert to CoffeeScript.
For in and for of comprehensions are some of the basic in the form in CoffeeScript. The Syntax of for loop in CoffeScript represents the loops with scenarios where it is represented with iteration as follows: K for k in [1… 5] // This represents for..in the loop with a declaration of values ranging from 1 to 5.
Compiling CoffeeScript into JavaScript usually results in JS that is fairly readable. You can convert snippets on the fly on the "Try CoffeeScript" tab of the CoffeeScript homepage, or via the CoffeeScript command line tool. There are also tools like decaffeinate that convert CoffeeScript source to modern JavaScript.
CoffeeScript is a lightweight language that compiles into JavaScript. It provides simple and easy to learn syntax avoiding the complex syntax of JavaScript.
The fastest loop is a for loop, both with and without caching length delivering really similar performance.
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()
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++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With