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.