The Little Book on CoffeeScript


  • On Amazon
  • ISBN: 978-1449321055
  • My Rating: 7/10

The Little Book on CoffeeScript is a brief introduction to the CoffeeScript language.

The book is a very quick read with its about 60 pages. However, it doesn't provide much that isn't already in the very good official documentation of the CoffeeScript project.

My notes


CoffeeScript is not a superset of JavaScript, so although you can use external JavaScript libraries from inside CoffeeScript, you'll get syntax errors if you compile JavaScript as is, without converting it.

You will need to know JavaScript in order to write CoffeeScript, as runtime errors require JavaScript knowledge.

You can convert JavaScript to CoffeeScript using the js2coffee project, especially useful when migrating JavaScript projects to CoffeeScript.

If you execute the coffee executable without any command line options, it'll give you the CoffeeScript console, which you can use to quickly execute CoffeeScript statements.

CoffeeScript Syntax

There are no semicolons in CoffeeScript, it'll add them automatically for you upon compilation.

Comments start with a hash character: # a comment. Multiline comments are also supported, they're enclosed by three hash characters.

White space is significant in CoffeeScript. In practice, this means that you can replace curly brackets with a tab.

CoffeeScript wraps up scripts with an anonymous function, keeping the local context, and automatically prefixes all variable assignments with var.

Sometimes it's useful to create global variables. You can either do this by directly setting them as properties on the global object (window in browsers), or with the following pattern:

exports = this
exports.MyVariable = "foo-bar"
In the root context, this is equal to the global object, and by creating a local exports variable you're making it obvious to anyone reading your code exactly which global variables a script is creating.

CoffeeScript removes the rather verbose function statement, and replaces it with a thin arrow: ->. The last expression in the function is implicitly returned, i.e. you don't need to use the return statement unless you want to return earlier inside the function.

CoffeeScript lets you specify arguments before the arrow, and it also supports default arguments: times = (a = 1, b = 2) -> a * b. You can also use splats to accept multiple arguments (denoted by ...).

Using the fat arrow (=>) instead of the thin arrow ensures that the function context will be bound to the local one.

If the if statement is on one line, you'll need to use the then keyword so CoffeeScript knows when the block begins. Conditional operators (?:) are not supported; instead you should use a single line if/else statement.

Instead of using the exclamation mark (!) for negation, you can also use the not keyword. In a similar fashion to not, CoffeeScript also introduces the is statement, which translates to ===. As an alternative to is not, you can use isnt.

Double quoted strings can contain #{} tags, which contain expressions to be interpolated into the string.

Example of iterating over an array: for name in ['Roger', 'Roderick', 'Brian']. You can also filter them: for name in ['Roger', 'Roderick', 'Brian'] when name[0] is 'R'.

For iterating over properties in objects, you have to use the of keyword instead of in.

If a range isn't prefixed by anything, CoffeeScript expands it out into an array: range = [1..5] # [1, 2, 3, 4, 5]. However, if the range is specified immediately after a variable, CoffeeScript converts it into a slice() method call: firstTwo = ["one", "two", "three"][0..1] # ["one", "two"].

To see if a value exists in an array, you can use the in operator.

One alias is @, which can be used in place of this. Another is ::, which is an alias for prototype.

CoffeeScript's existential operator ? returns true unless a variable is null or undefined: praise if brian?. You can also use it in place of the || operator: velocity = southern ? 40. If you're using a null check before accessing a property, you can skip that by placing the existential operator right before it: blackKnight.getLegs()?.kick().

CoffeeScript Classes

Classes are just as useful in JavaScript as they are in other languages and CoffeeScript provides a great abstraction. Behind the scenes, CoffeeScript is using JavaScript's native prototype to create classes; adding a bit of syntactic sugar for static property inheritance and context persistence. As a developer, all that's exposed to you is the class keyword: class Animal.

Defining constructors is simple – just use a function named constructor. By prefixing arguments with @, CoffeeScript will automatically set the arguments as instance properties in the constructor:

class Animal
  constructor: (@name) ->

CoffeeScript has extended support for fat arrows to classes, so by using a fat arrow for an instance method you'll ensure that it's invoked in the correct context, and that this is always equal to the current instance.

You can inherit from another class by using the extends keyword.

CoffeeScript Idioms

or is preferred over ||, and and is preferred over &&. This preference for natural-language style code also applies to using is instead of == and isnt rather than !=.

Compiling CoffeeScript

Cake is a super simple build system along the lines of Make and Rake. The library is bundled with the coffee-script npm package, and available via an executable called cake.

The Good Parts

CoffeeScript doesn't provide an abstraction over any of JavaScript's keywords, such as typeof, and as such, some design flaws in JavaScript's design also apply to CoffeeScript.

The typeof operator is probably the biggest design flaw of JavaScript, simply because it's basically completely broken. In fact, it really has only one use – checking to see if a value is undefined. For all other types of type checking, typeof fails rather miserably, returning inconsistent results depending on the browser and how instances were instantiated.

CoffeeScript already abides by a lot of strict mode's requirements, such as always using var when defining variables, but it's still very useful to enable strict mode in your CoffeeScript programs.

While I recommend enabling strict mode, it's worth noting that strict mode doesn't enable any new features that aren't already possible in JavaScript, and will actually slow down your code a bit by having the VM do more checks at runtime. You may want to develop with strict mode, and deploy to production without it.

Using with in CoffeeScript will throw a syntax error.

By ensuring global variables are explicit, rather than implicit, CoffeeScript removes one of the major sources of bugs in JavaScript programs.

CoffeeScript detects if you're using a reserved keyword, and escapes it if necessary.

CoffeeScript replaces all weak comparisons with strict ones (in other words, converting all == comparators into ===).

CoffeeScript generated JavaScript is JavaScript Lint compatible.

The Little Conclusion

The golden rule of CoffeeScript is: "It's just JavaScript". We want to embrace the limitations of compiling to JavaScript by only implementing things that can be expressing in simple JavaScript. When you run a script, there is no CoffeeScript interpreter running within the browser, no core library you have to include on the page, and ideally (although we bend this rule in a few places) no special helper functions generated alongside your code.