Xiaopei's DokuWiki

These are the good times in your life,
so put on a smile and it'll be alright

User Tools

Site Tools



CLI Examples

  • Compile a directory tree of .coffee files into a parallel tree of .js, in lib:
    coffee -o lib/ -c src/
  • Watch a file for changes, and recompile it every time the file is saved:
    coffee --watch --compile experimental.coffee
  • Concatenate a list of files into a single script:
    coffee --join project.js --compile src/*.coffee
  • Print out the compiled JS from a one-liner:
    coffee -bpe "alert i for i in [0..10]"
  • Start the CoffeeScript REPL:

Language Reference

First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code. You don't need to use semicolons ; to terminate expressions, ending the line will do just as well (although semicolons can still be used to fit multiple expressions onto a single line). Instead of using curly braces { } to surround blocks of code in functions, if-statements, switch, and try/catch, use indentation.

You don't need to use parentheses to invoke a function if you're passing arguments. The implicit call wraps forward to the end of the line or block expression.
console.log sys.inspect objectconsole.log(sys.inspect(object));


square = (x) -> x * x
cube   = (x) -> square(x) * x

fill = (container, liquid = "coffee") ->
  "Filling the #{container} with #{liquid}..."

Objects and Arrays

song = ["do", "re", "mi", "fa", "so"]

singers = {Jagger: "Rock", Elvis: "Roll"}

bitlist = [
  1, 0, 1
  0, 0, 1
  1, 1, 0

kids =
    name: "Max"
    age:  11
    name: "Ida"
    age:  9

// when using reserved words
$('.account').attr class: 'active'
log object.class

Lexical Scoping and Variable Safety

The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.

outer = 1
changeNumbers = ->
  inner = -1
  outer = 10
inner = changeNumbers()

If you'd like to create top-level variables for other scripts to use, attach them as properties on window, or on the exports object in CommonJS. The existential operator (covered below), gives you a reliable way to figure out where to add them; if you're targeting both CommonJS and the browser: exports ? this

If, Else, Unless, and Conditional Assignment

mood = greatlyImproved if singing

if happy and knowsIt

date = if friday then sue else jill

options or= defaults


it/coffee.txt · Last modified: 2013/08/19 07:22 (external edit)