Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Should You Learn CoffeeScript?

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

I'd imagine that I represent a large portion of the web development community. I'm very intrigued by CoffeeScript; I've even learned the syntax and used it in a few demos. However, I haven't yet taken the plunge and used it in a real project. It comes down to this one question for me: is CoffeeScript something that is truly worth investing time and effort into learning?

I wasn't sure, so I compiled a list of frequently asked questions (along with a few of my own), and asked some masters in the industry - on both sides of the fence - for their advice.

The Panel

Jeremy Ashkenas - The creator of CoffeeScript.

Brendan Eich

John-David Dalton

  • "I'm an opinionated JavaScript tinkerer, bug fixer & benchmark runner. I have a bachelor's degree in Multimedia Instructional Design, an awesome wife & a puppy."
  • @jdalton
  • FuseJS
  • Benchmark.js
  • uxebu Bio

Dave Ward

  • "I'm a software developer focusing on ASP.NET, jQuery, and web application usability."
  • @encosia

Marco Chomut

  • "I'm a Computer Scientist Extraordinaire living in the Washington, DC area. I specialize in web and mobile development, and love working with Django and Android."
  • @pewpewarrows

Trevor Burnham

James Padolsey

  • " I am, by profession, a JS Developer with extensive experience in front-end application development adopting new and cool JS/HTML5/CSS3 techniques while employing a variety of frameworks."
  • @padolsey
  • jQuery Cookbook
  • uxebu Bio

Nathan Smith

Ryan Florence

Oscar Godson

Alex MacCaw


1 - Perhaps the Most Common Question: if I'm a Reasonably Solid JavaScript Developer, is There Any Real Incentive for Me to Learn CoffeeScript?

Jeremy Ashkenas

Yes. CoffeeScript is not an entirely new and strange language. It exists to allow "reasonably solid" JavaScript developers to write the same code they were going to write in the first place, in a more readable and fluent way. The basic idea is to write what you mean, instead of writing within the limits of historical accident. For example, if I want to loop over every item in a list, in CoffeeScript, I can write what I mean:

    for item in list
      process item

Whereas in JavaScript, I partially obscure my intention, by writing:

    for (var i = 0, l = list.length; i < l; i++) {
      var item = list[i];
      process(item);
    }

CoffeeScript allows "reasonably solid" JavaScript developers to accomplish the latter by simply writing the former.

Other Incentives Include
  • The ability to write code that works in old versions of Internet Explorer without having to compromise or shim
  • Not having to worry about JavaScript pitfalls like trailing commas and automatic semicolon insertion
  • Cleaned up semantics where every language construct can be used as part of a larger expression
  • and a boatload of additional features listed on CoffeeScript.org

James Padolsey

If you're comfortable in JavaScript, and are able to create expressive APIs that suit you well, then I don't feel there is a sufficient incentive for learning CoffeeScript. Widening horizons and learning new programming paradigms and patterns is always good, but if you're learning CoffeeScript so it can eventually replace your need for JavaScript then there are other things to consider.

John-David Dalton

If you're great with JS, I don't think there is any real incentive to learn CoffeeScript. Things like accidental leaked globals, switch statement fall-throughs, and other potential JS gotchas can be handled by JS linters/text-editors and don't require a compile step / Node.js. Class sugar is so basic any JS developer can, if needed, simulate it in a handful of lines. I happen to like double equals ==, and switch statement fall-throughs, and know how best to write my JS.

Having to conform to someone else's rules of what they feel is appropriate doesn't mesh well with me.

Also, don't forget CoffeeScript isn't without its own warts.

Dave Ward

Continually exposing yourself to new perspectives and technologies is a critical part of keeping yourself relevant in our field.

Absolutely. Continually exposing yourself to new perspectives and technologies is a critical part of keeping yourself relevant in our field, and CoffeeScript is certainly a great candidate for that in the JavaScript space. Even if you ultimately decide that CoffeeScript doesn’t appeal to you, being able to write a bit of CoffeeScript should be a prerequisite to making an informed decision either way.

Nathan Smith

I have been using CoffeeScript for a few months now, as part of my job as a front-end dev on a Rails team. I don't know if I would say there's "incentive" to learning CoffeeScript if you already know JavaScript. I'm not sure there would be an incredible speed boost to be gained, because really there is no "best" tool for a job, only one you're most familiar with to accomplish a given task.

Though I enjoy the comfy feel of JavaScript (like a well broken-in pair of shoes), there is also a lot to like in CoffeeScript — the "unless" syntax, for example. I would liken using CoffeeScript to having a conversation with a friend who majored in English, correcting your grammar all the while. It's great if you want that guidance, but sometimes I just want to "keep it casual" and speak slang, without worrying about what that's going to translate into.

Note: I suspended judgment until after reading Trevor Burnham's book on CoffeeScript. Now that I know more about it, I'm fine using CS when I am on a team that already uses it, but I still tend to prefer JS for my own projects.

Ryan Florence

Absolutely. CoffeeScript is influencing TC-39's decisions (like paren-free, class syntax, arrow syntax, etc.). The future versions of JavaScript will likely look a lot like CoffeeScript. I decided to learn it after listening to Brendan mentioning its influence during his talk at TXJS.

If there is anything to learn about CoffeeScript is that it's _Just JavaScript™_. I consider it a part of our community and have really enjoyed learning it and using it. It doesn't feel like a different language when you use it.

Brendan Eich

(Limiting my response to responding to Ryan Florence's comments about TC39, except in my final paragraph.)

The influence of CoffeeScript on TC39 in practice is mostly me writing and proposing strawmen. None has yet stuck. I'm going to retool paren-free to be more like CoffeeScript in that newlines will be more significant in statement heads (this solves some nasty hard cases Waldemar Horwat identified, see es-discuss). But no indentation-based block structure.

Arrow function syntax was worth doing but it's not going to make it. Block lambdas are in better shape but not yet "in". As Jeremy said, “For the record, I too favor [block lambdas] if arrows in JS will need curlies to delimit blocks. Curlies or arrows, not both.”

That JS and CoffeeScript are formally co-expressive -- have the same semantics -- is huge. Yes, this means you could have just written JS. But productivity and beauty (in the eyes of some beholders) matter; syntax matters.

Oscar Godson

In short, no. The incentives to CoffeeScript are incentives, in my opinion, that are for developers who don't fully understand the language. For example, for...in loops and leaking globals and not understanding "this" fully. If you understand those things you don't make those mistakes in the first place, and if you do, you know what the problem is right away and know how to fix them. Having an entire transpiled language to fix common mistakes seems like overkill.

Marco Chomut

Out of professional curiosity, you should always be exploring new languages, technologies, libraries, and frameworks.

There are a few different approaches to answering this question. First and foremost, out of professional curiosity, you should always be exploring new languages, technologies, libraries, and frameworks. The worst thing that can happen to you as a developer is to become stuck in a rut. If the first language you learned was COBOL, ColdFusion, or PHP, and that's still the breadth of your knowledge five years later, you're just asking to become obsolete. Then again, it's equally worse to jump ship onto the new flavor-of-the-month every time something mildly interesting appears in your news reader or Twitter feed. Have a healthy curiosity while maintaining reasonable skepticism.

Arriving back on topic, if you and your co-workers are already well-versed in restricting yourselves to the "good parts" of JavaScript, and are painfully aware of its idiosyncrasies, than CoffeeScript probably won't offer you much. It's a more Ruby or Python-like approach to syntax for the language that does everything it can to prevent you or your team from shooting themselves in the foot. But it's not for everyone.

Trevor Burnham

Obviously I have a financial stake in this question (my book was released by PragProg in May), so you can take my words with a grain of salt. But yes, I think that learning CoffeeScript is worth the time. It doesn't take much effort to learn; CoffeeScript is basically the sum of a few dozen syntactic sugars on top of JavaScript. And the reward is that you get to write more beautiful code, when you want it. For instance, some JavaScripters use CoffeeScript just for their unit tests.

Some folks complain about having to use a compiler on top of JavaScript, but some of JavaScript's flaws—like automatic global creation when the var keyword is omitted (see here)—more or less necessitate the use of other tools, or strict mode. CoffeeScript is one such tool, and is easily among the most popular.

Alex MacCaw

My CoffeeScript programs end up as being about half the length of the equivalent source written in JavaScript.

Absolutely; in fact I'd say there was even more of an incentive to learn CoffeeScript if you're a solid JavaScript developer. CoffeeScript certainly requires some JavaScript profiency, there's no getting away from it. JavaScript knowledge is a pre-requisite, especially when it comes to debugging.

However, for good JavaScript developers, CoffeeScript offers a lot of advantages, such as fixing common bugs concerning global variables, semicolons and equality comparisons. Frankly, even the best JavaScript developers make these sort of simple mistakes from time to time.

The other major advantage CoffeeScript offers me over JavaScript is syntactical sugar such as shorter function declarations, comprehensions and a simple class abstraction. My CoffeeScript programs end up as being about half the length of the equivalent source written in JavaScript, with twice the clarity.


2 - is CoffeeScript Targeted at JavaScript Developers? or, is it for Devs Who Prefer Other Languages, Like Ruby, and Haven't Yet Learned the Ins and Outs of JS?

Jeremy Ashkenas

The core idea with CoffeeScript is to express JavaScript semantics in as readable and minimal a syntax as we can find.

CoffeeScript is targeted at JavaScript developers. It certainly borrows ideas from other dynamic languages, including Python, Ruby and Perl. But ultimately, the core idea with CoffeeScript is to express JavaScript semantics in as readable and minimal a syntax as we can find.

John-David Dalton

It seems to me developers who prefer languages like Ruby gravitate more towards CoffeeScript than those that don't. Although, it's common to find developers having love / hate opinions about it in any group.

Nathan Smith

I think CoffeeScript is targeted at people that understand JavaScript, but for whom it isn't their language of choice. Otherwise, (obviously) they would prefer to just be writing JS. Whether one knows the ins and outs of JS when starting with CS, it is essential if one is to get the most out of using CS.

Oscar Godson

I work at Yammer with a lot of senior JavaScript engineers; none use it. I noticed that the friends who do use it and are extremely happy about it are Rails people. For example, at Posterous, they use it but don't have any real JavaScript engineers. We have Rails people here, but they only do Rails - not JavaScript.

Ryan Florence

I'd have to defer to Jeremy for that one, but I do think it appeals mostly to Rubyists who are finding they spend most of their day in JavaScript. CoffeeScript knowledge is not a substitute for JavaScript knowledge. Scope is kind of different; other than that, it's just a cleaner syntax.

Marco Chomut

I'd definitely say that it's targeting both existing JavaScript developers and those coming from other dynamic languages who are somewhat new to the front-end web world. I personally discovered it after already having a decent amount of "raw" JS experience, and it was refreshing to work with what I imagine a modern-day client-side language would look like. While it's just my personal approach to learning things, I don't think I would have dove straight into CoffeeScript without any prior knowledge of the language it was built upon.

It's important to always have at least a rudimentary understanding of whatever "black boxes" of abstraction exist in your toolkit.

Trevor Burnham

If you're someone who likes JavaScript but wants to write more expressive code, CoffeeScript is going to be the obvious choice.

CoffeeScript's goal is to stay as close as possible to the underlying JavaScript while improving on the language's syntax. That makes it very different from, say, Dart, or GWT, or something that reorders code like TameJS. So I think that if you're someone who likes JavaScript but wants to write more expressive code, CoffeeScript is going to be the obvious choice.

Obviously it's disproportionately popular in the Ruby world, since it's borrowed many Ruby-isms like postfix if/unless and has an extremely prominent evangelist in dhh, but it's also quite popular in the Node.js world, which says a lot.

Alex MacCaw

I've used JavaScript for years, and wrote the O'Reilly book on JavaScript web applications. I think you could say I've learnt the 'ins and outs' of the language. That said, I personally plan to never write plain JavaScript again, not because I don't like the language, but because I love writing CoffeeScript so much.

CoffeeScript is for people who deeply understand and respect JavaScript.


3 - When Dart was announced, it was met with immediate slander by much of the JS community. Though not an entirely different language, the same is partially true for CoffeeScript. Are some developers simply afraid of learning yet another new thing, or are their criticisms justified?

Jeremy Ashkenas

With the release of Dart, the web development community was faced with the peril of Google forcing a new, nonstandard language into a shipping web browser.

Dart is a different story. With the release of Dart, the web development community was faced with the peril of Google forcing a new, nonstandard language into a shipping web browser. As we know well from the web -- once you ship something in a browser, it tends to be there forever. In addition, Dart retreats from the dynamism of JavaScript, and instead exists as a somewhat static language, where types can be checked at compile time, but are erased at runtime. The JavaScript community perceived this as a cynical gesture to make Java developers feel more at home in Dart, being able to write types that appear similar to Java types, even though they're treated as comments when the program runs. It's not just JavaScript developers being wary of the Dart push, browser implementors are wary as well.

Now, let's take the CoffeeScript case. CoffeeScript has felt threatening to a surprising number of JavaScript developers, in a way that other languages have not. You don't hear JS programmers worrying about other new languages like Clojure or Scala, or even compile-to-JS languages like GWT or Objective-J in anything approaching the same volume.

Note that I'm not talking about people who simply choose to continue to use JavaScript -- I continue to use JavaScript for many projects as well. I'm talking about the fearful rhetoric of "I won't use your library because you wrote it in CoffeeScript", or "CoffeeScript makes you forget how to write JavaScript."

CoffeeScript feels threatening to JavaScript developers precisely because it's so close to JavaScript.

Because the semantics are the same, every CoffeeScript program is fully interoperable with JavaScript, and vice-versa. You may already be using a library written in CoffeeScript without even knowing it (like Zombie.js, Riak-JS, or xml2js). In addition, CoffeeScript is actually being used -- it's currently the 13th most popular language on GitHub.

As as JavaScript developer, confronting this situation -- where there's a fully compatible alternative to JavaScript, with the same performance profile -- forces you to answer the question: "why haven't you tried CoffeeScript yet?" Many of the posts that we're seeing are developers justifying their answer to that question for themselves. If I hadn't tried CoffeeScript yet, I'd probably be writing the same kind of posts.

James Padolsey

The real battle is creating clean, intuitive and maintainable APIs.

Dart's slightly different. One, it's from Google! i.e. that massive monopoly that we're supposed to be wary of. Beyond the various political issues, Dart doesn't seem to bring anything to the table other than a more Java-esque syntax, which many developers aren't too fond of, myself included. I prefer to stick to the most expressive API/languages I have at my disposal. When it comes to CoffeeScript, though, I am cautious because really, it's just JavaScript, but with a completely different syntax. JavaScript's malleable enough for me to create the APIs and functionality that I need. I don't much care for convenience sugar unless it really enhances my ability to write good code. Some of CoffeeScript's features, like destructuring assignment and the existential operator, are really quite awesome, but to be honest, they're just minor sweetness, and similar functionality can be gained in JavaScript (see JS 1.7 for destructuring assignment too!), although with a little more verbosity. The real battle is creating clean, intuitive and maintainable APIs. CoffeeScript isn't going to help you a great deal there. Like I said, it's sugar.

John-David Dalton

I don't think it's being afraid of something new. For me at least, it's more about not wanting to over-engineer and having more control over my JS.

Dave Ward

It’s difficult to speak for others, but I don’t get the impression that many JavaScript developers are avoiding CoffeeScript because they avoid new things. If anything, I think most developers who are aware of CoffeeScript at all are probably on the early adopter’s end of the curve.

In particular, I believe that reluctance toward adding CoffeeScript’s compilation step into client-side development is objectively justified, not related to any previous investment in learning JavaScript.

Nathan Smith

With any potentially disruptive new technology, those who have staked their claim on the current way of doing things tend to go through the five "stages of grief."

This was my experience, anyway...

  1. Denial — "I'll never use CoffeeScript." (or Dart)
  2. Anger — "I wish people would shut up about it already!"
  3. Bargaining — "Okay, I guess it has *some* good parts."
  4. Depression — "I can't believe I have to learn this."
  5. Acceptance — *Shrug* ~ "Use the best tool for the job."

That said, there are some justifications to the criticisms of CoffeeScript (and Dart). However, whereas CoffeeScript attempts to adhere to the "spirit" of JavaScript (terse code, etc), the end-game for Dart is to get developers writing an entirely different language altogether (preferably interpreted in a browser's VM, instead of being precompiled to JS). Dart is more akin to Java than JavaScript.

The most valid criticism against any language that would attempt to supplant JavaScript is that JS has the world's largest install base of any language runtime (on desktop browsers, server, and mobile devices). It might not be perfect, but as far as distribution goes, it "just works."

Brendan Eich has already expressed his interest in seeing aspects of CS folded back into future versions of ECMAScript. By contrast, Dart has been met with harsher criticism from not only JS developers, but from the WebKit community.

Oscar Godson

Yes and no. I tend to be more critical of things before I've tried them, but I did try CoffeeScript to see what all the hype was about. It was nice, but it's not worth it. Why have a compiled language to *just* help you with common JS warts and to make JS more "pretty"? That's what puts me off about it. JavaScript engineers do tend to be elitist though, I agree with that, but in this case I believe it's for a good reason. The reason being, don't write a totally different language to fix some warts about it.

Ryan Florence

[...] We’re just so tired of fragmentation.

CoffeeScript and Dart aren't even comparable. Dart aims to replace JavaScript, CoffeeScript is nothing more than a nice coat of paint. You can use CoffeeScript and still "always bet on JS". I think front-end devs are happy to learn new things (our environment is always broken, you'd have to like learning stuff to survive), we're just so tired of fragmentation. It's completely justified to freak out if you see "ActiveX 2.0" coming. CoffeeScript is not a threat to JavaScript.

Marco Chomut

I believe both reactions were equally justified (although when Google is involved, people always tend to exaggerate their opinions one way or the other for whatever reason). CoffeeScript was a re-imagining of JavaScript from the Ruby and Python communities. Dart was a re-imagining from a subset of the Java community. Language biases aside, I honestly don't believe that Java-fying an already dynamic and (arguably) verbose language is the correct approach.

It probably didn't help that the JavaScript community was already allergic to the idea of Dart before it was even announced, due to the set of "leaked" correspondance surrounding it.

Trevor Burnham

Of course some of the criticisms of CoffeeScript are justified. I mean, "significant whitespace is evil" is a lame one, but "it divides the community" is legit. There's something to be said for JS being a lingua franca. But you look at very common JS mistakes like forgetting a comma in a multi-line object literal (or adding an extra one at the end of the last line), and it causes your whole app to crash... for a certain kind of programmer (myself included), not having to deal with that is a big breath of fresh air.

I think CoffeeScript and JS are going to peacefully coexist for the foreseeable future, and there are gonna be haters, and that's fine. That's how you know it's a real programming language.

Alex MacCaw

CoffeeScript doesn't intend to replace JavaScript, or abstract it away, but rather to enhance it.

As others have mentioned, Dart is a completely different beast to CoffeeScript, and many of the criticisms directed at Dart were regarding implementation details and Google's approach, rather than just the existence of another language. Frankly, CoffeeScript is an entirely different language to Dart.

Google took rather a walled garden approach to Dart, and I get the impression they didn't really look outside the confines of their company for inspiration. Whether this was because of some sort of Not Invented Here syndrome, or the fact that they needed a language that would appeal to their Java developers, I'm not sure. However, Dart strikes me as something that is very specific to Google's needs, rather than something that's applicable at large.

CoffeeScript doesn't intend to replace JavaScript, or abstract it away, but rather to enhance it. So, not only are the languages completely different, but the motives behind them are very different. Thus it's difficult to compare criticism between the two.


4 - Is it fair to assume that, if you're against the idea of CoffeeScript, then you're likely also against CSS preprocessors, like Sass and Less? Or, do you see a specific distinction between the two (as I do)?

James Padolsey

I've never used Sass or Less so I can't really comment. I will say that the general idea is the same in that they're all slightly heightening the level of abstraction, allowing you to quickly get at functionality without having to type the verbose alternative. I will say that the thing keeping me from picking up CoffeeScript is very different to what would keep me from picking up a CSS preprocessor.

John-David Dalton

I don't work heavily with CSS and haven't used a CSS preprocessor but I can understand the need to manage the cluster of vendor prefixes. I'm also not as comfortable with CSS as I am with JS.

Nathan Smith

I don't think that is an entirely accurate assumption. While there might be some who are against all preprocessing of client-side code, with Sass (and Compass) you get a layer atop CSS that's very "close to the metal" in terms of syntax. One of the benefits of Compass is the ability to write one line that is transformed into multiple lines of vendor prefixed code. One needn't memorize different variations on the same styling that will ultimately be deprecated when a standard is agreed upon. Sass (with Compass) example:

#foobar
  +background(linear-gradient(#fff, #ccc))

That reads cleanly, and is somewhat similar to what the standard might become in CSS.

CoffeeScript, on the other hand, adds a new syntactic layer that seeks to be a departure from JavaScript, incorporating idioms from other languages that are not native to JS.

Sass adds variables, color math, and a slew of things that cannot be done in CSS alone. Whereas, CoffeeScript provides an alternative approach to what JavaScript is already perfectly capable of doing. I believe that's why we're having this discussion — Some see value in that. Others don't.

Oscar Godson

I personally have nothing against CSS preprocessors because they add functionality. I don't use them because I'm a purist you could say, but they do save time with less typing - particularly for people who do lots of CSS coding. They also don't aim to fix "broken" things - just extend it. I don't use it and don't see myself ever using it for personal stuff but I'm not opposed to using it.

Ryan Florence

There is a distinction. SASS, Less, Stylus etc. all bring something to CSS that it doesn't already have.

There is a distinction. SASS, Less, Stylus etc. all bring something to CSS that it doesn't already have: logic--it turns your CSS into an application. CoffeeScript doesn't bring anything "new" to JavaScript in the same way, which is why it's so debatable. Not using a CSS preprocessor isn't really even debatable for anything non-trivial.

Marco Chomut

CoffeeScript provides cleaner syntax...

I'm going to have to agree with the other answers here that the CSS "equivalents" of CoffeeScript, such as SASS or Less, are often judged quite differently. For me, SASS is always a default on any new project that I work on, while CoffeeScript continues to be debatable. CoffeeScript provides cleaner syntax, does its best to keep a developer shielded from the bad parts of JavaScript, and allows you to avoid prototype-based inheritance with its built-in class structure. SASS on the other hand offers a slew of (very-necessary) features to CSS that you would otherwise not be able to have. Variables, functions, mixins, the list goes on and on. CoffeeScript doesn't really offer any of these meta-features to JavaScript, and really just boils down to syntactic sugar.

Trevor Burnham

I'm honestly amazed that people are still using Sass/SCSS.

Sass is an interesting example because it went through a big split itself: Originally, it was a fully whitespace-significant alternative to CSS, and of course some people loved that and others hated it. Now it comes in two flavors: The whitespace-significant "Sass Classic" syntax, and the CSS superset SCSS. They're both annoyingly strict; the "Sass Classic" compiler will yell at you if you use so much as a semicolon. Then TJ Holowaychuk came along and created Stylus, which lets you use whitespace-significant syntax and curly-brace syntax... in the same file! It's a much more elegant solution, and I'm honestly amazed that people are still using Sass/SCSS.

Which isn't to say that CoffeeScript should start accepting curly braces (there would be some ambiguous cases). My point is just that CSS preprocessors aren't really about cleaner/terser syntax the way CoffeeScript is. (The SCSS syntax is more popular than Sass Classic, probably because designers can keep using the CSS snippets they're used to without running them through a converter.) They're about doing things in a totally different way. CSS isn't really a language; CSS preprocessors (with their variables and functions) are.

Rebuttle from Nathan Smith:

CSS *is* a language. Just not a "programming" language. I see his point though, preprocessors allow for declarative, functional programming.

Alex MacCaw

Well, I don't think that's necessarily the case. I personally enjoy Less and Stylus, as much as I enjoy CoffeeScript. However, I'm not a fan of HTML abstractions such as HAML and Jade. I evaluate each technology independently. I'm not for or against preprocessors in general.


5 - A frequent criticism of CoffeeScript is that, if everyone uses it, we may get to a point when nobody remembers (or ever learned) how to write actual JavaScript. Is this a valid concern?

Jeremy Ashkenas

Nope -- CoffeeScript exposes a subset of JavaScript semantics. If you learn how to write CoffeeScript, almost by definition you'll know how to write JavaScript. Learning isn't a zero-sum game. Learning one language or dialect doesn't prevent you from knowing others.

In fact, just as people who are comfortable speaking several languages find it easy to pick up more; programmers who know more than one dialect of JavaScript may be better able to learn new concepts and idioms.

John-David Dalton

No. As it is CoffeeScript compiles to JS so developers still have to deal with JS when debugging, for the time being, and can still use JS through the supported embedding syntax.

- http://jashkenas.github.com/coffee-script/#embedded
- https://bugs.webkit.org/show_bug.cgi?id=30933
- https://bugzilla.mozilla.org/show_bug.cgi?id=618650

Dave Ward

Various tools and frameworks have been “compiling” to HTML for nearly as long as HTML has existed

No, I don’t think that’s likely.

Various tools and frameworks have been “compiling” to HTML for nearly as long as HTML has existed, yet knowledge of (and appreciation for) the generated HTML markup has only increased during that time. With most abstractions, you inevitably find yourself dealing with edge cases that force you to learn more deeply about the underlying technology. If anything, a simple abstraction over something more daunting often provides an appealing onramp for new developers, eventually leading them to learn more about the abstracted topic than they would otherwise have been comfortable with.

Nathan Smith

If CoffeeScript goes "mainstream" then more people will take an interest in the JavaScript language itself.

I actually think (hope) maybe the opposite will be true. I think that if CoffeeScript goes "mainstream" then more people will take an interest in the JavaScript language itself. I have met quite a few designers who didn't care about JavaScript at all, but learned how to cut and paste jQuery snippets. Before long, they're saying "Man, I really need to learn JavaScript."

Just as jQuery ignited interest in JS amongst designers with its "reads like CSS" selectors, I think that perhaps CoffeeScript will be that "gateway drug" to greater JS understanding, except for Rubyists. Either way, those who already know JS have a leg-up.

Oscar Godson

Have you been to StackOverflow recently? Try asking a question about JavaScript. I once asked about doing some date parsing (to get the next Wed.) and someone sent me an entire jQuery plugin. It ended up being a one liner and the jQuery plugin got the most votes compared to the right one line answer. This has happened with jQuery where people just pick up jQuery and never bother to learn JavaScript. On Twitter I overheard someone asking about cookie sessions and someone suggested they use jQuery and include a $.cookie plugin. Im worried that CoffeeScript is going to end up like this where people will be including this for simple apps or when they just dont really want to understand JS.

Ryan Florence

You can't write CoffeeScript without knowing JavaScript. You are debugging the JavaScript. You're using third-party libs that are JavaScript. You can't get away from it (the great flaw in using CoffeeScript for real world applications). So no, its not a valid argument for being against CoffeeScript.

The fact that this argument is flawed is a solid argument to not use CoffeeScript. If you can't break from JavaScript, what's the point?

Marco Chomut

Similar arguments were made around the time that jQuery was becoming quite popular. I don't believe that it was a valid concern then, and I don't think it is now. Learning CoffeeScript will also require you to at some point buckle-down and learn the underlying JavaScript. This isn't really something that you can avoid, until the day comes (if ever) that browsers parse and execute it natively. You're going to run into the odd error or interaction that will force you to understand what it's translating into.

Trevor Burnham

You shouldn’t use CoffeeScript without knowing JavaScript.

What Ryan said.

You shouldn't use CoffeeScript without knowing JavaScript, although you can learn both at the same time. I mean, there must be a million people out there who are using JavaScript without really knowing JavaScript. A lot of them have other primary languages, and they'll never really like JavaScript as much as they like Ruby, or PHP, or Java, so they only learn as much as they need to get by. That's the sort of crowd my book is mainly aimed at. It's like "Hey, let's learn this hip new language, and along the way we'll fill in the gaps in our JavaScript knowledge."

Alex MacCaw

On the contrary, it's quite the opposite. I don't think this is a valid concern. As the others have stated, JavaScript knowledge is a requirement for writing CoffeeScript. Thus by writing CoffeeScript I think your JavaScript knowledge should, if anything, improve.

The JavaScript generated by the CoffeeScript compiler is top notch, and by browsing through it you certainly learn a few tricks.

However, I completely disagree that the fact you can't break from JavaScript is an argument not to use CoffeeScript. CoffeeScript is a lightweight curated subset of the language, improving it's syntax and only presenting the 'good parts'. In other words, I think it's an improvement.


6 - One argument in favor of CoffeeScript that I rarely see put forth is that it can make you a better JavaScript developer - particularly if you're somewhat new to the language. Similar to Rails, a huge array of best practices are baked into the compiler. Do you see benefit in that aspect? Use CoffeeScript to become a better JavaScript developer?

Jeremy Ashkenas

A large number of users have reported learning new tricks and patterns from reading their compiled JavaScript.

Yes. A large number of users have reported learning new tricks and patterns from reading their compiled JavaScript.

But having best practices built in to the compiler doesn't mainly benefit beginners -- the benefit is to long-term programmers who can take full advantage of having a concise, readable way to express their JavaScript intentions in code -- without having to constantly keep best practice patterns in mind. A best practice that can be enforced and generated by a compiler is better than a best practice that has to be remembered and manually typed out every time.

James Padolsey

The only problem I see with taking this approach is that you're not really learning JavaScript, and there's so much magic going on that you won't necessarily be appreciating the lengths that you might have to go to in order to get similar things done in JavaScript. CoffeeScript is easier for these tasks.

It will teach you to become a better programmer, I think, but if you want to learn JavaScript, then learn it, purely.

John-David Dalton

I think you can take the "it makes you a better JS developer" and apply that to existing JS libs/frameworks. I learned a lot from digging into and fixing issues in libs like Dojo, jQuery, MooTools, and Prototype. The code produced by CoffeeScript is extraneously verbose and promotes micro-optimizations (which isn't necessarily helpful and not a "best practice").

I would not look to CoffeeScript or its compiled JS to improve my JS skills and would rather look to mature battle hardened JS libs.

Dave Ward

If someone wants to become a better JavaScript developer, there are less circuitous routes. I think the main things that make JavaScript difficult for beginners are more conceptual than syntactical. CoffeeScript doesn’t change the fact that you need to understand concepts like closures, asynchronous programming, and continuation passing to write non-trivial JavaScript code.

Nathan Smith

I think there is some truth to this. If you are consistently checking what JavaScript is output by the CoffeeScript compiler, I think there are some insights to be gleaned. For instance, declaring all variables at the beginning of a function, to prevent variable hoisting.

Additionally, the concept of closures is introduced automatically. This might seem frustrating at first, if just trying to create a global variable, directly inline (emitting something from the server-side in HTML). Due to this, CoffeeScript enforces good habits, such as explicitly attaching variables to the global object, if that is indeed what you mean to do...

// Global variable in CoffeeScript
window.foobar = 'something'

//=====//

(function() {
  // CoffeeScript output.
  window.foobar = 'something';
}).call(this);

// Versus:

(function() {
  // Manual typo.
  foobar = 'something';
})();

That's not to say such lessons cannot be learned apart from using a transpiler, but if someone new to JavaScript sought to use CoffeeScript as a way to learn about JS concepts, it might be an interesting place to start. Though, for JS beginners, reading canonical books like "JavaScript: The Good Parts" would probably be more helpful.

Oscar Godson

How do you learn or become better at something you've been shielded from? If you never have to worry about global vars leaking how do you know later when working with vanilla JS? It's like giving someone a camera with auto-focus who's never used a camera before and then expecting them to know how to use a film camera and adjust the focus, ISO, etc by manual means.

Ryan Florence

My hand-written JavaScript is pretty different from what CoffeeScript spits out.

I think developers who aren't very experienced in JavaScript have something to learn from the compiler's output. Take the ?= and ||= operators, CoffeeScript shows them how to solve that problem in JavaScript.

But they are also going to have a hard time debugging code they don't understand. I don't think these people can effectively use CoffeeScript.

My hand-written JavaScript is pretty different from what CoffeeScript spits out; it's also better looking. I think there's more to learn by reading the source code of some of our community leaders and established JS libraries than from the compiler.

Marco Chomut

If, as a developer, you weren't already exposed to the finer portions of JavaScript (either through Douglas Crockford's JSLint or Anton Kovalyov's JSHint), then CoffeeScript will definitely be a decent crash-course in the subject. But only if you take the chance to really understand why CS made certain decisions in the language. If you rush through it and merely try to push out a working prototype as fast as possible, you're only harming yourself in the long run. I mentioned it before in a previous answer, but being unaware of some of the inner workings of your black boxes is very dangerous and counter-productive.

Trevor Burnham

Sounds like you've been attending my talks; I put this argument forward all the time.

It's interesting that you mention Rails. A lot of people learn Ruby by learning Rails. A lot of people learn JavaScript by learning jQuery. But if you learn that way, you're not going to see the whole language. By contrast, you work through something on CoffeeScript, you're going to see the edges. You're going to learn all about this and prototype inheritance and typeof/instanceof and iterating through object keys and array values, and a hundred other things that JS noobs ask about on Stack Overflow every day.

So yeah. I see learning CoffeeScript as one path to becoming a knowledgeable JavaScripter. Certainly not the only one, but one that's fun and rewarding.


7 - Clearly, if you're a Ruby developer, CoffeeScript will be infinitely more appealing to you, as the syntax is fairly similar. For real world projects, where developers have deadlines, is CoffeeScript not simply a way to get the job done more quickly, with less language shuffling? What's wrong with that, if anything?

Jeremy Ashkenas

Some Rubyists say that CoffeeScript looks like Ruby, Pythonistas say that CoffeeScript looks like Python, and I've heard Haskellers say that CoffeeScript looks like Haskell.

I'm afraid that this is a silly question. Some Rubyists say that CoffeeScript looks like Ruby, Pythonistas say that CoffeeScript looks like Python, and I've heard Haskellers say that CoffeeScript looks like Haskell. The truth of the matter is that CoffeeScript semantics are just JavaScript semantics -- there's definitely no less "language shuffling" involved.

James Padolsey

I fear it will become acceptable to forgo the vital learning curve of JavaScript and simply rest falsely assured that the code you write in CoffeeScript works just like it would in that-other-language-you-know. For a team with a deadline I can definitely see the appeal of having a more unified development environment. Ruby and CoffeeScript are a cute match -- much more so than JavaScript and Ruby. I think an understanding of JavaScript is vital, especially at this early stage (debugging can still be a nuisance).

John-David Dalton

Depends on their setup. CoffeeScript, like JS libs, has bugs from release to release (even some which affect cross-browser use) which can cause existing CoffeeScript code to break.

Also, debugging still requires digging through raw JS and may not necessarily be an easy task as CoffeeScript applications become more complex.

Unlike JS libs which can live on CDNs, the sugar around CoffeeScript has to be compiled for every JS file (unless compiled together). This can make CoffeeScript generated JS less ideal for separate third-party scripts. CoffeeScript adds yet another "something" the team will have to familiarize themselves with and become proficient in, which costs time/money and could be avoided by simply using JS (JS lib + linter).

Dave Ward

As someone who has spent quite a bit of time in the .NET world, I’ve seen that argument used to support drag ‘n drop development and some particularly leaky abstractions over HTML, CSS, and JavaScript. That experience has left me extremely skeptical about the long-term value of focusing on up-front productivity at the expense of understanding your development stack.

Nathan Smith

I wouldn't say it's a way to avoid "language shuffling." Though CoffeeScript and Ruby might share some syntactic sugar, each has its own ways of dealing with things. While CS will no doubt look familiar to Ruby developers, there is still a learning curve.

If you are under the gun on a deadline, deciding to use CoffeeScript is probably not going to help you get that work done any sooner. As with any new language, you need to set aside some time to get familiar with it, make beginner mistakes, and finally end up at a place where it becomes second nature.

I think the danger to Ruby developers is hoping that CoffeeScript will gloss over some perceived mysterious aspects inherent to JavaScript.

While you might end up typing less overall characters in a *.coffee file, you still need to care about what ends up in the *.js file. That comes with experience, not (only) with new syntax.

Ryan Florence

You write in one language, but debug in another...

As for "less language shuffling" I assume you mean it's like Ruby everywhere in your app--that is totally false. You write in one language, but debug in another language and neither is Ruby, so it's actually more shuffling.

If JavaScript's syntax is slowing you down, then you need to learn how to use your text editor or learn how to type. There is nothing faster about CoffeeScript. Introducing CoffeeScript into your workflow actually increases "shuffling":

A lot of people gloss over the debugging issue but 20% of the day we write bugs, the other 80% we fix them (don't deny it). Debugging is a big issue.

You are debugging code you didn't write. You have to figure out what the compiler is doing, and then figure out why the code is not doing what you wanted. Then you have to go to your CoffeeScript and figure out how to fix it in a different syntax. Usually it's not that bad, but when using some of the fancier features of CoffeeScript it can get really "machine code" looking. One line in CoffeeScript can turn into several lines of crazy looking stuff (see here), that, again, you didn't write, so you have to figure out why it looks that way, and then why it's broken.

This back-and-forth "shuffling" is a weird step that slows you down because it's not _your_ code you're looking at. I find I'm back to doing a lot of console.log in my code instead of using break points and watch expressions, etc., which is a total shame, and slower. But it's the fastest way for me to "shuffle" between the JavaScript I'm debugging and the CoffeeScript I'm writing.

Trevor Burnham

Will CoffeeScript get the job done more quickly? Certainly some prominent JavaScript/Ruby pros have reached that conclusion for themselves.

Rubyists are certainly easier to sell on CoffeeScript than, say, Java programmers. But the most common questions I get from Rubyists are along the lines of "Wait, why do we need a separate language? Why can't we just compile Ruby to JS?" And I try to explain to them that, well, compiling "a = b" from Ruby into JS would require you to check whether b is a function, and if it is then run it and return its value... and compiling "x = y + 1" would require you to fire up a BigDecimal library, because all Ruby numbers are infinite-precision... and so on. Those folks have to learn that, look, when you're in the browser, you're on JavaScript's turf and you've got to make peace with it. It could be worse. It could be statically typed.

Will CoffeeScript get the job done more quickly? Certainly some prominent JavaScript/Ruby pros (like 37signals' Sam Stephenson, creator of Prototype.js) have reached that conclusion for themselves. Obviously it depends on a lot of factors... sometimes what you need is a fresh perspective, and a new language can give you that.

Alex MacCaw

CoffeeScript isn't inherently Rubyish.

That's a pretty leading question, and I don't think that assumption is necessarily valid. CoffeeScript isn't inherently Rubyish, just as it's not inherently Pythonist. It borrows features from both languages but ultimately its schematics are inspired by JavaScript. The aim of CoffeeScript is not to abstract away JavaScript for developers who don't want to learn it, such as the now defunct RJS. As such, it doesn't help with language shuffling.


8 - Many Might Argue That CoffeeScript Allows for More Beautiful and Maintainable Code. for Example, Creating a Class in CS is Considerably More Intuitive and Readable Than What We Might Write With Plain JavaScript.

It's not surprising that many will prefer the cleaner and shorter:

class MyClass
  constructor: ->
    alert 'constructor'
  
  doSomething: ->
    alert 'doing something'
    
c = new MyClass()
c.doSomething()

Over...

var MyClass = (function() {
  function MyClass() {
    alert('constructor');
  }
  
  MyClass.prototype.doSomething = function() {
    alert('doing something');
  };
  
  return MyClass;
})();

c = new MyClass();
c.doSomething();

My question is: does CoffeeScript's readability alone warrant its usage?

Jeremy Ashkenas

You can write undreadable code in any language.

You can write undreadable code in any language ... but yes -- one of the main focuses of CoffeeScript is readability: expressing JavaScript concepts and patterns in as minimal and readable a way as we can find.

Your "class" example is a good one. If you want to make many objects that share common methods in JavaScript -- it's not easy to accomplish. There are many ways to break the "prototype" object while you try to set up the prototype chain. You're left either writing unreadable boilerplate every time you wish to chain two prototypes together, or using a helper library that hides basic object orientation from you. CoffeeScript's classes are a simple way to define your constructor functions along with their prototypal properties and prototype chain. The side effect is the readability of simply writing what you mean:

    class Square extends Shape

... instead of a half dozen lines of prototype manipulation code in JavaScript:

    function Square() {
      ...
    };
    var tempConstructor = function(){
      this.constructor = Square;    
    };
    tempConstructor.prototype = Shape.prototype;
    Square.prototype = new tempConstructor;

James Padolsey

Naturally, because I’ve worked more with JavaScript, it’s more readable to me than CoffeeScript.

That's not the JavaScript I would write, but I see your point. CoffeeScript can have great readability and most of the CS code I've seen is both terse and expressive, but I don't think this necessarily translates to "more intuitive". Naturally, because I've worked more with JavaScript, it's more readable to me than CoffeeScript. Again, this seems to be about taste, and is very much influenced by prior language exposure. A Ruby person would probably understand the CoffeeScript code sooner than the JavaScript, but it would be the opposite for, say, a PHP or Java developer, where keywords play a central role in class and function definition. In CoffeeScript you have very minimal and expressive operators which aren't always as clear.

John-David Dalton

No. Developers have different opinions on what they consider readable. CoffeeScript is similar to JS libs in that they all add syntactic sugar and each developer/team has their own preference (MooTools, jQuery, Dojo, CoffeeScript, CoffeeScript+libs, and on and on).

Dave Ward

If you want syntactic sugar around structuring your code, there are JavaScript libraries to help with that without requiring the obtrusive compilation step.

If you want syntactic sugar around structuring your code, there are JavaScript libraries to help with that without requiring the obtrusive compilation step.

Considering this question in the overall context of the others, the developer who doesn’t yet understand JavaScript needs more than a somewhat similar analog to their server-side language’s implementation of classical inheritance. I believe putting the “class” pseudo-keyword in front of a developer coming from a typical object oriented language may even be harmful in the long run.

Nathan Smith

"Readability" is subjective. I think you've touched on something with the "class" example. For developers coming from a classical programming background (C#, Ruby, etc), CoffeeScript probably feels like a breath of fresh air. To me, having learned JavaScript as my first "real" programming language, thinking in terms of classes feels foreign.

In my opinion, the perfect blend of CS and JS would be var added automagically, and not needing to write unnecessary parenthesis or curly braces. However, I could do without the automatic return at the end of each function.

I am also not a fan of how CS hijacks the for in to become an i++ loop — requiring instead that you write for of to be able to iterate through objects (when *.length isn't present).

Oscar Godson

This might be because JavaScript isn't a class based language. It's prototypal, and that scares people who aren't used to it. PHP or Rails developers come to JS, and don't know how to use it properly. So they come up with hacks to make it work and even look like other languages. This isn't the answer. If you do need to use classes, you can write a mini-lib and make it clean like:

var Ninja = Person.extend({
  init: function(){
    this._super( false );
  },
  dance: function(){
    // Call the inherited version of dance()
    return this._super();
  },
  swingSword: function(){
    return true;
  }});

// via http://ejohn.org/blog/simple-javascript-inheritance/

The only real difference is no parenthesis. I actually like Brendan Eich's idea of paran-free JS, but I like the idea of it being baked in and not completely changing the language.

Ryan Florence

I review code on gerrit from my team every day. Some JavaScript, some CoffeeScript. I have as hard a time following what they're trying to do in one syntax vs. the other. It's perhaps more verbally readable at times, but that has yet to make it more understandable for me. Take this line for example:

scores = (student["assignment_#{@assignment.id}"].score for own idx, student of @gradebook.students when student["assignment_#{@assignment.id}"]?.score?)

That's 160 columns of verbally readable code straight out of our app but I have no idea what it's doing. The fun part is that you end up debugging things like this.

There are some aspects to CoffeeScript that are less readable.

The fat arrow => binds the context to the function, which sounds great, but it encourages deep nesting, an anti-pattern.

Couple that with significant whitespace over several lines of code and you've got a mess. Unstructured code with callbacks and lots of if else going on is extremely hard to follow: there's no closing bracket for me to place my cursor over and see where I'm at with my text editor. Some say, "Don't write code like that". I don't write all the code I work with.

Also, not all APIs have functions as the last argument to their signature, so you end up with some commas floating around at the beginning of lines, which looks really weird next to the rest of CoffeeScript's generally appealing look.

On the flip side, I've noticed that the class syntax hits a logical chord in people who aren't JavaScript experts but experts in some other language(s). Suddenly they grasp that they can write modular front-end code instead of chaining jQuery down to oblivion. I personally don't use class, or write JavaScript the way you did in the example, but I think its a useful syntax for good programmers less familiar with JavaScript.

Trevor Burnham

As far as readability is concerned, there's no substitute for good documentation. I look at the annotated source for Backbone.js, and I think, "Wow." It'd be maybe 30% fewer lines if it were written in CoffeeScript, but it'd only be marginally easier to understand.

I think the bigger win is in writability. It's not just fewer keystrokes (typing is rarely a bottleneck for coding); it's less to think about. A common Node.js idiom is writing:

  if (err) throw err;

...at the top of callbacks. I could save that as a snippet, I guess, but I'd much rather just punch in the CoffeeScript equivalent.

It just takes fewer brain cycles. That way, I can focus more on the core of the callback.

Alex MacCaw

Sure, that's a good reason to learn CoffeeScript, or indeed any high level language. Readability is a crucial part to developing, maintaining and extending code in any language. CoffeeScript takes this a step further by using whitespace, meaning that badly formatted code will simply fail to compile.

Of course it's possible to write ugly code in any language, but I definitely think CoffeeScript has an inherit aesthetic beauty to it, in both the language and the community; much more so than traditional JavaScript.


Closing Arguments

Jeremy Ashkenas

I'd like to file my general objection to the way in which these questions are framed. They create false drama where none needs to exist. CoffeeScript is a fun little language that attempts to push JavaScript in a certain direction: How minimal and readable a syntax can we find to express the famous good parts of JavaScript. If you enjoy it, that's great; if you don't, that's great as well -- JavaScript is a wonderful language. Because CoffeeScript and JavaScript share semantics, they'll always get along just fine. Personally, I write a good deal of both.

Interviewer's Notes: Absolutely. It was never my intention to create a flame war, when, ultimately, we're dealing with helpful tools. That can never be a bad thing! That said, the questions I've provided are the ones that I found to be most frequently asked on Twitter, blogs, and social networks. Even if they're unfounded, it's important to acknowledge that they are being asked, and discuss them. :)

Ryan Florence

I think CoffeeScript is an excellent choice for hobbyist and one-man operations. On a team, I would advise against it if you aren't already down the path.

Trevor Burnham

What Ryan said. Learn JavaScript. It's an awesome language. But it's not my favorite language, because there's CoffeeScript.

John-David Dalton

+1 to Ryan Florence's side note.

Nathan Smith

I don't think anyone can deny that Jeremy Ashkenas has created something remarkable. The fact we're all talking about it testament to that. I would encourage anyone who has dug-in their heels against using CoffeeScript to at least give it a shot. Having done so myself, I still prefer JavaScript, but at least now I can appreciate why it's appealing to others.


Further CoffeeScript Resources

  • JSConf 2011 Presentation
  • A Cup of CoffeeScript
  • Rocking Out with CoffeeScript
  • A Case Against CoffeeScript

  • A Question for the Readers

    Now that some of the best in the business have offered there own opinions, I'd like to hear from you in the comments. While most of these questions came courtesy of social networks and blog posts, this last question is one that I was personally most interested in learning the answer to.

    One of my only concerns with using CoffeeScript is that debugging the generated JavaScript could potentially be a huge concern. Have you found this to be the case?

    Let me know below!

    Advertisement