Array iteration in JavaScript has a rather archaic syntax,
reminiscent of an older language
like C rather than a modern object-orientated one. The introduction of ES5
improved that situation somewhat, with the forEach()
function, but that still requires a
function call every iteration and is therefore much slower. Again,
CoffeeScript comes to the rescue, with a beautiful syntax:
for name in ["Roger", "Roderick", "Brian"] alert "Release #{name}"
If you need the current iteration index, just pass an extra argument:
for name, i in ["Roger the pickpocket", "Roderick the robber"] alert "#{i} - Release #{name}"
You can also iterate on one line, using the postfix form:
release prisoner for prisoner in ["Roger", "Roderick", "Brian"]
As with Python comprehensions, you can filter them:
prisoners = ["Roger", "Roderick", "Brian"] release prisoner for prisoner in prisoners when prisoner[0] is "R"
You can also use comprehensions for iterating over properties in
objects. Instead of the in
keyword, use
of
:
names = sam: seaborn, donna: moss alert("#{first} #{last}") for first, last of names
The only low-level loop that CoffeeScript exposes is the while
loop. This has similar behavior to the
while
loop in pure JavaScript, but has
the added advantage that it returns an array of results (i.e. like the
Array.prototype.map()
function):
num = 6 minstrel = while num -= 1 num + " Brave Sir Robin ran away"
Get The Little Book on CoffeeScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.