CoffeeScript - for..in comprehensions



The for..in comprehension is the basic form of comprehension in CoffeeScript. Using this, we can iterate the elements of a list or array.

Syntax

Suppose we have an array of elements in CoffeeScript as ['element1', 'element2', 'element3'] then you can iterate these elements using the for-in comprehension as shown below.

for element in ['element1', 'element2', 'element3']
   console.log element

Example

The following example demonstrates the usage of for…in comprehension in CoffeeScript. Save this code in a file with name for_in_comprehension.coffee

for student in ['Ram', 'Mohammed', 'John']
   console.log student

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c for_in_comprehension.coffee

On compiling, it gives you the following JavaScript. Here you can observe that the comprehension is converted into the for loop.

// Generated by CoffeeScript 1.10.0
(function() {
  var i, len, ref, student;

  ref = ['Ram', 'Mohammed', 'John'];
  for (i = 0, len = ref.length; i < len; i++) {
    student = ref[i];
    console.log(student);
  }

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee for_in_comprehension.coffee

On executing, the CoffeeScript file produces the following output.

Ram
Mohammed
John 
coffeescript_comprehensions.htm
Advertisements