CoffeeScript - Postfix comprehensions



Just like postfix if and unless, CoffeeScript provides the postfix form of the Comprehensions which comes handy while writing the code. Using this, we can write the for..in comprehension in a single line as shown below.

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

#postfix for..of comprehension
console.log key+"::"+value for key,value of { name: "Mohammed", age: 24, phone: 9848022338}

Postfix for..in comprehension

The following example demonstrates the usage of postfix form of the for..in comprehension provided by CoffeeScript. Save this code in a file with name for_in_postfix.coffee

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

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

c:\> coffee -c for_in_postfix.coffee

On compiling, it gives you the following JavaScript.

// 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_postfix.coffee 

On executing, the CoffeeScript file produces the following output.

Ram
Mohammed
John 

Postfix for..of comprehension

The following example demonstrates the usage of postfix form of the for..of comprehension provided by CoffeeScript. Save this code in a file with name for_of_postfix.coffee

console.log key+"::"+value for key,value of { name: "Mohammed", age: 24, phone: 9848022338}  

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

c:\> coffee -c for_of_postfix.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var key, ref, value;

  ref = {
    name: "Mohammed",
    age: 24,
    phone: 9848022338
  };
  for (key in ref) {
    value = ref[key];
    console.log(key + "::" + value);
  }

}).call(this);

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

c:\> coffee for_of_postfix.coffee 

On executing, the CoffeeScript file produces the following output.

name::Mohammed
age::24
phone::9848022338
coffeescript_comprehensions.htm
Advertisements