Chapter 3. CoffeeScript Idioms

Every language has a set of idioms and practices, and CoffeeScript is no exception. This chapter will explore those conventions, and show you some JavaScript to CoffeeScript comparisons so you can get a practical sense of the language.

Each

In JavaScript, to iterate over every item in an array, we could either use the newly added forEach() function, or an old C style for loop. If you’re planning to use some of JavaScript’s latest features introduced in ECMAScript 5, I advise you to also include a shim in the page to emulate support in older browsers:

for (var i=0; i < array.length; i++)
  myFunction(array[i]);

array.forEach(function(item, i){
  myFunction(item)
});

Although the forEach() syntax is much more succinct and readable, it suffers from the drawback that the callback function will be invoked every iteration of the array, and is therefore much slower than the equivalent for loop. Let’s see how it looks in CoffeeScript:

myFunction(item) for item in array

It’s a readable and concise syntax, I’m sure you’ll agree, and what’s great is that it compiles to a for loop behind the scenes. In other words, CoffeeScript’s syntax offers the same expressiveness as forEach(), but without the speed and shimming caveats.

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.