A for-loop conversion from JavaScript to CoffeeScript

I was stumbling along StackOverflow when I ran into this question:

How can I convert a Javascript for-loop to Coffee? With this example:

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

The answer: (I've since edited and updated the Stackoverflow answer)

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

http://jashkenas.github.com/coffee-script/\#loops

This answer works for this contrived case.

What happens when you have a case like this:

for (var x = 0; x < myArray.length; ++x)
  alert(x);

What's the answer smarty pants? If you answered:

alert(i) for i in [0 .. myArray.length-1]

You get a pass if myArray has anything in it. What will happen if myArray is an empty (not null) array? Go ahead and execute it. Go here to the CoffeeScript page, and paste this code in the "Try CoffeeScript", I'll wait.

myArray = []
alert(i) for i in [0 .. myArray.length-1]

What's that? You say it returned "0" and "-1"???

The secret is in the ".." which implies "=>" or "<=" 
and the "..." implies "&lt" or "&gt".

So this is probably what you expect:

myArray = []
alert(i) for i in [0 ... myArray.length]

It's too bad the loops section at this time doesn't mention this.

CoffeeScript is a great tool. Here is another tool that allows you to convert JavaScript to CoffeeScript. Try our examples here and see what the tool generates. Hint: it isn't always optimized.

If you made it this far, you should follow me on Twitter.

-JP

comments powered by Disqus