For this blog post, we’re going to discuss ranges, loops and comprehensions in CoffeeScript.
Also check out the previous installments:
Again a feature that is heavily inspired by Ruby. Using a range we can define an array of consecutive numbers by only specifying the first and the last number.
This is a so-called inclusive range which is denoted by the two dots separating the bounding numbers. CoffeeScript also provides the concept of an exclusive range which is denoted by three dots instead of two.
In this case the number of the upper boundary is excluded. Ranges are a small addition to the syntax that can come in handy from time to time.
The for .. in syntax in CoffeeScript is used for iterating over an array while the next example show how a for .. of loop is used for iterating over the properties of an object.
In the example where we iterate over an array, the for .. in loop can be more compact using the postfix notation.
How nice is that! Let’s look at some more sweet syntax that CoffeeScript brings us. We can use the ‘when’ keyword for filtering.
Filters are supported by both for .. in and for .. of loops. We can also obtain the current index when looping over an array.
This is only possible when using for .. in loops. We can also use the 'by' keyword to loop over an array with fixed-size steps.
Again, this is only possible when using for .. in loops. Besides all these nice syntax additions for for … in loops, there is also a quite helpful keyword that’s only available when using for .. of loops. We can use the 'own' keyword for iterating over properties that are only defined on the object itself and not on any prototype(s).
Let’s take this a bit further by diving into comprehensions.
Everything is an expression in CoffeeScript, which means that this also applies to loops. What better way to demonstrate this than a simple code example? Suppose we want to create an array with even numbers by looping over another array of numbers. This is how it can be solved using the CoffeeScript way.
A for loop in CoffeeScript always returns an array with the result of every iteration which in this case are the even numbers from the first array. Note that we need to enclose this comprehension with parentheses because otherwise we only get the last even number instead of an array with all the even numbers.
If you’re not yet impressed by this language feature, then checkout the following one-line FizzBuzz implementation.
To make things complete, CoffeeScript also provides a while loop.
numbers = [1..10] console.log numbers # Outputs [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
That’s it for now. Until next time.