Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Comprehensions

In a lot of our iterating examples, we’ve had very simple code blocks we wanted to execute, like this one:

Example: (source: iterating_arrays.coffee)


myLetters = ["a", "b", "c", "d"]

for letter in myLetters
  console.log letter.toUpperCase()


Because we are using a single line code block with our for loop, we are able to take advantage of what CoffeeScript calls comprehensions. Comprehensions are, essentially, loops and their code blocks on the same line.

Here’s what that same example would look like using comprehensions:

Example: (source: iterating_arrays_comprehension.coffee)


myLetters = ["a", "b", "c", "d"]

console.log letter.toUpperCase() for letter in myLetters


Example: (source: iterating_arrays_comprehension.js)


(function() {
  var letter, myLetters, _i, _len;

  myLetters = ["a", "b", "c", "d"];

  for (_i = 0, _len = myLetters.length; _i < _len; _i++) {
    letter = myLetters[_i];
    console.log(letter.toUpperCase());
  }

}).call(this);


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint