O'Reilly logo

The Little Book on CoffeeScript by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. They’re also deprecated and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required