The Fixed Parts

Now that we’ve covered some of JavaScript’s warts that CoffeeScript can’t fix, let’s talk about a few that CoffeeScript does fix. In my mind, the following features are some of the best reasons to use CoffeeScript; they fix some of the most common mistakes developers make when writing JavaScript. While this is more of an academic discussion, you should still find the rest of this chapter useful, especially when making the case to use CoffeeScript!

A JavaScript Subset

CoffeeScript’s syntax only covers a subset of JavaScript’s, the famous Good Parts, so already there’s less to fix. Let’s take the with statement for example. This statement has for a long time been “considered harmful,” and should be avoided. with was intended to provide a shorthand for writing recurring property lookups on objects. For example, instead of writing:

dataObj.users.alex.email = "info@eribium.org";

You could write:

with(dataObj.users.alex) {
  email = "info@eribium.org";
}

Setting aside the fact that we shouldn’t have such a deep object in the first place, the syntax is quite clean. Except for one thing. It’s confusing to the JavaScript interpreter, which doesn’t know exactly what you’re going to do in the with context, and forces the specified object to be searched first for all name lookups.

This really hurts performance and means the interpreter has to turn off all sorts of JIT optimizations. Additionally, with statements can’t be minified using tools like uglify-js ...

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.