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.


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


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

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

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);


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

c:\> coffee

On executing, the CoffeeScript file produces the following output.


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

Kickstart Your Career

Get certified by completing the course

Get Started