O'Reilly logo

The Little Book on CoffeeScript by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Map

As with forEach(), ES5 also includes a native map function that has a much more succinct syntax than the classic for loop, namely map(). Unfortunately, it suffers from much the same caveats as forEach() (i.e., its speed is greatly reduced due to the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required