
- CoffeeScript Tutorial
- CoffeeScript - Home
- CoffeeScript - Overview
- CoffeeScript - Environment
- CoffeeScript - command-line utility
- CoffeeScript - Syntax
- CoffeeScript - Data Types
- CoffeeScript - Variables
- CoffeeScript - Operators and Aliases
- CoffeeScript - Conditionals
- CoffeeScript - Loops
- CoffeeScript - Comprehensions
- CoffeeScript - Functions
- CoffeeScript Object Oriented
- CoffeeScript - Strings
- CoffeeScript - Arrays
- CoffeeScript - Objects
- CoffeeScript - Ranges
- CoffeeScript - Splat
- CoffeeScript - Date
- CoffeeScript - Math
- CoffeeScript - Exception Handling
- CoffeeScript - Regular Expressions
- CoffeeScript - Classes and Inheritance
- CoffeeScript Advanced
- CoffeeScript - Ajax
- CoffeeScript - jQuery
- CoffeeScript - MongoDB
- CoffeeScript - SQLite
- CoffeeScript Useful Resources
- CoffeeScript - Quick Guide
- CoffeeScript - Useful Resources
- CoffeeScript - Discussion
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.