![CoffeeScript Tutorial](/coffeescript/images/coffeescript-mini-logo.jpg)
- 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..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