Sunday, January 27, 2013

CoffeeScript control structures

Coffeescript has really few control structures. Most of the loops, for example, can be written as comprehensions over arrays, objects and ranges. Comprehensions should be able to handle most places where you otherwise would use a loop, each/forEach, and map.

For example:
fruits = ['Apple', 'Orange', 'Banana', 'Grapes']
console.log fruit for fruit in fruits

Would result in this JavaScript:
var fruit, fruits, _i, _len;

fruits = ['Apple', 'Orange', 'Banana', 'Grapes'];

for (_i = 0, _len = fruits.length; _i < _len; _i++) {
  fruit = fruits[_i];

The real work happens at the console.log fruit for fruit in fruits line. It calls the console.log function for each fruit in fruits.

CoffeeScript also has a few cool tricks in working ranges. They are quite handy if you need row numbers for tables. Here is an example:

tableRowNum = (num for num in [10..1])  
console.log c for c in tableRowNum

The only real loop construct that CoffeeScript has is the while loop. But its better than JavaScript's because it can be used as an expression. It also works nicely with another keyword: the until keyword. For all intents is a while not loop in javascript.

# Econ 101
if this.studyingEconomics
  buy()  while supply > demand
  sell() until supply > demand

So far, CoffeeScript is surprising me. It's certainly not boring me.