CoffeeScript - for..of comprehensions



Just like Arrays, CoffeeScript provides containers to store key-value pairs known as objects. We can iterate objects using the for..of comprehensions provided by CoffeeScript.

Syntax

Suppose we have an object in CoffeeScript as { key1: value, key2: value, key3: value} then you can iterate these elements using the for..of comprehension as shown below.

for key,value of { key1: value, key2: value, key3: value}
   console.log key+"::"+value

Example

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

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

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

c:\> coffee -c for_of_example.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_example.coffee

On executing, the CoffeeScript file produces the following output.

name::Mohammed
age::24
phone::9848022338 

Note − We will discuss arrays, objects, and ranges in detail in individual chapters later in this tutorial.

coffeescript_comprehensions.htm
Advertisements