There are a couple of different approaches to looping in CoffeeScript. The designers of CoffeeScript felt that the majority of loops are really just iterating over a collection. Thus the majority your looping needs can be served using a for-each style loop. The syntax for doing so looks about how you would expect
Here we have a loop over the trees in theÂ forest. Pretty easy. What if I really need to know the index of the element on which I was operating? Unlike for-each loops in many languages which assume that the index of and element in an enumeration in meaningless CoffeeScript offers a way out
By passing in a secondÂ parameterÂ to the for loop you can gain access to an element which contains the index. If you donâ€™t have a collection but wish to execute some operation multiple times you can either use a for loop syntax on a range or use a while loop.
For loop with range:
Perhaps the coolest feature of loops in CoffeeScript are that you can perform filtering on the elements as youÂ iterateÂ over them. If I only wanted to perform an action on my forest when the tree was birch then I can create an implicit if by doing
Now letâ€™s say that the trees in the forest are a bit more complex that before and we wanted to filter on a property, thatâ€™s no problem: