Introducing CoffeeScript

Basic Syntax

To execute the function, just give the CoffeeScript REPL (read-eval-print loop) the name of the function, followed by parentheses (that is, execution):

 coffee> hello_world() 

CoffeeScript functions return their final value, much as Ruby methods do. In the case of this hello_world function, that means the function is returning "undefined". You can make that a bit better by having the function return the string, rather than print it:

 coffee> hello_world = (name) -> "Hello there, #{name}!" 

Then, you can say:

 coffee> console.log hello_world('Reuven') Hello there, Reuven! 


 coffee> hello_world('Reuven') 'Hello there, Reuven!' 

depending on whether you want to get the string back or just print it to the console.

CoffeeScript provides the basic JavaScript data types, but it adds a great deal of syntactic sugar, as well as additional methods, that make those data types easier to deal with. For example, CoffeeScript uses Python-style triple-quoted strings.

The "existential" operator, a question mark (?), allows you to determine whether a variable contains something other than null or undefined values. This is better than just checking for the truth of a value, which will lead to (literal!) false negatives if a value contains 0 or the empty string. For example:

 v = 0  if v     console.log "yes" else     console.log "no"  if v?     console.log "yes" else     console.log "no" 

The above code example shows how CoffeeScript implements if/else control blocks. There also is an "unless" operator, which (as you might expect) inverts the output from if. CoffeeScript also provides postfix "if" and "unless" statements—something you might recognize from Perl and Ruby.

You also can see another element of CoffeeScript above, this one taken from Python. Whitespace and indentation are significant, and allow you to remove much of the curly braces and begin/end of many other languages. Unlike Python, however, colons aren't necessary after the "if" and "else" statements.

CoffeeScript arrays are like JavaScript arrays, but with all sorts of nice syntax added. Want a ten-element array? Just use this:

 a = [0..9] 

and you'll get it, using the built-in "range" operator. (This doesn't work for letters though.) You can retrieve ranges as well:


You can assign to a range, without worrying about the precise length of what you're splicing in:

 a[5..7] = ['a', 'b'] 

You also can retrieve substrings using this syntax:

 coffee> alphabet[5..10] alphabet[5..10] 'fghijk' 

CoffeeScript strings, like JavaScript strings, are immutable. Thus, you cannot assign to a substring:

 coffee> alphabet[5..10] = [5] alphabet[5..10] = [5] [ 5 ]  coffee> alphabet alphabet 'abcdefghijklmnopqrstuvwxyz' 

JavaScript objects, which can be used like hashes (aka "dictionaries" or "associative arrays") work just as they do in JavaScript, but with some easier syntax. For example, in JavaScript, you would write:

 person = { first_name: 'Reuven', last_name: 'Lerner' } 

In CoffeeScript, you can say:

 person =     first_name: 'Reuven'     last_name: 'Lerner' 

Once again, using Python-style indentation instead of curly braces makes it more compact but no less readable.

Loops and Comprehensions

You can loop through arrays with

 for number in a     console.log number 

I should point out that this will print each number on a line by itself and will return an array of undefined values (because console.log doesn't return a value, and "for" returns an array).

Objects can be accessed using the similar for..of loop:

 for key, value of person   console.log "key = '#{value}'" 

Note that for..of loops work on any JavaScript object. Because every object can contain properties, and because arrays are objects, you even can assign properties to arrays: = 'bar' 

Using a loop, you'll continue to see the values in the "a" array. But using a for..of loop, you'll get not only the array elements (whose keys are the indexes), but also "foo". Additionally, note that if you're interested only in the properties defined on an object, rather than on its prototype, you can add the "own" keyword:

 for own key, value of person   console.log "key = '#{value}'" 

In this particular case, there will be no difference. But if "person" were to have a prototype, and if the prototype were to have keys of its own, you would see the prototype's keys and values, and not just those for the "person" object.

But the need for these and for..of loops is reduced dramatically in CoffeeScript because of comprehensions, an idea that comes from Python that takes some getting used to, but that offers a great deal of power and simplicity once you do so, allowing you to combine map, reduce and filter in a single statement. For example, you can take a list of numbers:

 coffee> a = [100..110] [ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110 ] 

And you then can multiply each number by 5, much as you would do with "map" in Ruby or Python, but using "comprehension" syntax:

 coffee> i*5 for i in a [ 500, 505, 510, 515, 520, 525, 530, 535, 540, 545, 550 ] 

You also can select out some values. Suppose, for example, you want to operate only on those elements that are odd. You can say:

 coffee> i*5 for i in a when i%2 [ 505, 515, 525, 535, 545 ] 

is completing his PhD in learning sciences at Northwestern University.


Comment viewing options


Javascript is still alive

Anonymous's picture


The setup was confusing. How

Sannomo's picture


Quite bad code formatting for

Anonymous's picture

Quite bad code formatting for a whitespace-aware language.