Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 398
Shamoon Avatar asked Sep 07 '11 16:09

Shamoon


People also ask

How do you use a loop in 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.

How can we convert CoffeeScript code in JavaScript?

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.

Is CoffeeScript easy?

CoffeeScript is a lightweight language that compiles into JavaScript. It provides simple and easy to learn syntax avoiding the complex syntax of JavaScript.

Which loop is faster JavaScript?

The fastest loop is a for loop, both with and without caching length delivering really similar performance.


2 Answers

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()    
like image 111
jontro Avatar answered Oct 17 '22 01:10

jontro


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++ 
like image 39
Olivier Refalo Avatar answered Oct 17 '22 02:10

Olivier Refalo