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 function calls):

var result = []
for (var i=0; i < array.length; i++)
  result.push(array[i].name)

var result = array.map(function(item, i){
  return item.name;
});

As we covered in Chapter 1, CoffeeScript’s comprehensions can be used to get the same behavior as map(). Notice we’re surrounding the comprehension with parens, which is absolutely critical in ensuring the comprehension returns what you’d expect (i.e., the mapped array):

result = (item.name for item in array)

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.