npm install -g coffee-script
// watch & recompile an entire project as you work
coffee -o lib/ -cw src
Compile .coffee
files to a single .js
file.
coffee -j js/app.js -c src/*.coffee
Coffeescript:
# Assignment:
number = 42
opposite = true
JS:
var number, opposite;
number = 42;
opposite = true;
Coffeescript:
number = -42 if opposite
JS:
var number;
if (opposite) {
number = -42;
}
Coffeescript:
square = (x) -> x * x
var square;
square = function(x) {
return x * x;
};
Coffeescript:
# Arrays:
list = [1, 2, 3, 4, 5]
var list;
list = [1, 2, 3, 4, 5];
Coffeescript:
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
JS:
var math;
math = {
root: Math.sqrt,
square: square,
cube: function(x) {
return x * square(x);
}
};
Coffeescript:
race = (winner, runners...) ->
print winner, runners
JS:
var race,
slice = [].slice;
race = function() {
var runners, winner;
winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return print(winner, runners);
};
Coffeescript:
# Existence:
console.log "I knew it!" if elvis?
JS:
if (typeof elvis !== "undefined" && elvis !== null) {
console.log("I knew it!");
}
Coffeescript:
# Array comprehensions:
cubes = (math.cube num for num in list)
var cubes, num;
cubes = (function() {
var i, len, results;
results = [];
for (i = 0, len = list.length; i < len; i++) {
num = list[i];
results.push(math.cube(num));
}
return results;
})();