
Intro to CoffeeScript - aseemk
http://aseemk.com/blog/intro-to-coffeescript
======
zalew
> _What I find sad, though, is that most people who dislike CoffeeScript don’t
> truly know it. They haven’t taken the time to really learn it, or even try
> it. Their reactions are usually knee-jerk, or based on fallacies. [...] The
> explanation for most people’s dislike of CoffeeScript is probably our
> natural resistance to new things and our comfort in what we know._

Oh, wow. I've been using CoffeeScript for about a year for the usual front-end
crap, not long ago I re-evaluated Coffee for the second time before starting a
full-JS project and certainly won't use it. While I'm a fan of bracketless
whitespace significant langs (Python, Sass, Haml) CS's is just bonkers and you
never know when a single space will bite you by compiling to a completely
different code you had in mind. The ecosystem is weak not to say non-existent
comparing to JS, and every JS solution and example out there from minor jquery
stuff through SPA frameworks to mobile UI builders is in, well, JS (duh!), so
public code reusability becomes a ridiculous task of converting to CS, only to
compile it to JS once again. I still use CoffeeScript for small front-end
work, meanwhile for any bigger work I find CS an obstacle over JS, and an
unnecessary step between my idea and working code; especially when the JS
ecosystem has grown a lot of tools to help you deal with what pisses you off
(underscore/lodash as an example come to mind).

And from the slide:

> _And as of July 2013, it 's also the tenth most popular language on GitHub!
> That's more than Objective-C, ActionScript, C#, Clojure, Go, Groovy, Scala_

Yay github charts as evidence of industry value.

Knee-jerk, fallacies, resistance? Call it what you want and good luck.
Meanwhile, I will use coffee to keep me awake, not to write apps with.

//edit: care to explain the downvote?

~~~
brightsize
I _love_ CS myself. To me, in terms of aesthetics, CS is to JS what Scala is
to Java. I _have_ been bitten by the whitespace issue that you mention though.
I don't recall the circumstance but an indent that was off just a bit did not
cause the compiler to complain, but did cause it to generate code that I did
not intend. It took some debugging of the JS output to find that one, and it
certainly gives one pause to think how similar bugs might slip into the code
undetected. I've never encountered this kind of problem with Python, so I
wonder if the CS compiler just needs to be a little fussier/smarter with its
whitespace processing?

~~~
zalew
Compilers/interpreters complain about code that's invalid. Since the code is
valid it shouldn't interfer, the problem is in the language's syntax design
that's prone to shooting yourself in the foot. The design lets you mix
indentations, something that Python won't let you do.

A very simple scenario where hell is a keystroke away:

    
    
        hello =
          woot: 1
          yay: 2
          funfunfun: (x) -> x + 1
        
        hello2 =
            woot: 1
            yay: 2
           nowthatsfun: (x) -> x + 1
    
    

Other:

    
    
        y1 = (x) -> 
            x + 1
    
        z1: (x) -> 
            x + 1
          
          
        y2 = (x) -> 
            x + 1
    
        z2 = (x) -> 
            x + 1
    

[http://js2coffee.org/#coffee2js](http://js2coffee.org/#coffee2js)

Those are fairly visible here, not so much on a huge codebase (not to mention
with some callback hell attached). You can write perfectly legal code that
just doesn't work as expected.

//edit:

worth a read, with more trap examples [http://ruoyusun.com/2013/03/17/my-take-
on-coffeescript.html](http://ruoyusun.com/2013/03/17/my-take-on-
coffeescript.html)

~~~
lucasvo
Your second example though exists in exact the same way in python and ruby.
Some people prefer to hunt for missing comma's and brackets, others for
spaces.

I think that's a matter of taste. Coming from python, I've quite enjoyed
coffee-script's syntax and I've actually done something in between, using
brackets for objects just because I like the readability of it, but avoiding
all semicolons and taking advantage of the indentation for code blocks.

~~~
zalew
Yes, the second is a bit forced, couldn't remember what was the other case I
banged my head against the desk. I'm a Python programmer too, maybe that's why
I expected the language will prevent me from mismatching blocks of code. Well,
even sass and haml (which aren't full-blown programming languages) aren't that
easy to mess up. Using Python convention (4 spaces indent) instead of the
unofficial but common ruby/js/sass ones (2 spaces) helps a bit to spot out
obvious bad indents, but still - in general I don't find the language
trustworthy enough to jump into something big with it (for all the reasons I
listed before).

btw added a link above with some more syntax gotchas.

------
sdevlin
> The explanation for most people’s dislike of CoffeeScript is probably our
> natural resistance to new things and our comfort in what we know.

This is a mildly insulting, as is the invocation of Blub.

CoffeeScript doesn't have a ton of exotic features. String interpolation, list
comprehensions, and class definitions (!) are all familiar to programmers from
other languages.

I'm guessing that a lot of people have weighed CoffeeScript's feature set
against its overhead and decided the trade just isn't worth it.

~~~
tlrobinson
What overhead? If you mean performance, there's actually basically no runtime
performance overhead in most cases. In fact, if you use CoffeeScript's "for"
loops have a performance advantage over JavaScript Array's map()/forEach()
methods.

I used to have a similar opinion but was forced to use CoffeeScript on a
project and haven't looked back.

~~~
recursive
The overhead of having an additional dependency. The more moving parts there
are, the more things can break.

~~~
tlrobinson
Then why don't you write assembly?

~~~
masklinn
1\. Since when can you write web applications in assembly?

2\. Languages built upon assembly generally have better user experience,
better tooling, better semantics and effectively no more dependencies than
assembly. CoffeeScript has very slightly better user experience, worse
tooling, identical semantics and more dependencies than javascript.

~~~
tlrobinson
1\. That's missing the point, but since you asked, Emscripten and Native
Client.

2\. I disagree that CS's user experience is only "very slightly" better, but
that's very subjective.

Tooling is a somewhat valid complaint but it's a young platform and it's
improving (source maps, etc).

Semantics aren't quite identical (scoping, implicit return values, "fat arrow"
functions).

How does CS have more dependencies than any other compiled language? The only
dependency is a compiler.

~~~
masklinn
> 1\. That's missing the point, but since you asked, Emscripten

Has LLVM grown an assembly frontend? Emscripten is more or less an LLVM
backend.

> and Native Client.

These are no more web applications than writing firefox extensions at this
point.

> Semantics aren't quite identical (scoping, implicit return values, fat arrow
> functions).

For the most part, this is minimal syntactic sugar, not significantly
different semantics.

> How does CS have more dependencies than any other compiled language?

It does not, the point is that javascript has no dependency, and that if
you're going to add a compiler dependency you might as well go for real
changes.

~~~
tlrobinson
> Has LLVM grown an assembly frontend? Emscripten is more or less an LLVM
> backend.

I don't know, probably, but LLVM's IF is essentially machine independent
assembly anyway.

But again, missing the point.

------
sehrope
This is a fantastic slide deck. The per slide comments below are great too.
Particularly on an iPhone as you read them simultaneously.

We've been using CoffeeScript for a bit over a year now and never looked back.
All of our front end code is written in CS and I can't imagine writing JS
again. It's just _objectively_ better. Less code to write, easier to read,
minimal cruft, and a joy to use.

The only hiccup was getting the compilation integrated into the build process.
We handle it with direct loading of the CS files while working locally with
coffescript.js loaded as well. That way code changes are available as soon as
you refresh the page. Our build script for the app (when packaging it up for
staging/prod) pre compiles the CS files so there's no compilation lag in prod.

I've been experimenting with node.js for a side project and its pretty easy to
setup a project entirely in CS. There's a pretty good template with
CoffeeScript/Express/Mongoose to use as a template here:
[https://github.com/olafurnielsen/form5-node-express-
mongoose...](https://github.com/olafurnielsen/form5-node-express-mongoose-
coffeescript)

~~~
aseemk
Thanks for the compliment! The viewer doesn't quite look and feel right on the
iPhone, but glad you didn't think so. =)

I don't know what your stack is, but FYI on Node we use Connect/Express
middleware that automatically compiles CoffeeScript files to JS -- and in
production, caches the results -- before serving them. No manual
building/compiling/packaging needed at any point. You might find something
similar for your stack if you haven't already looked:

[https://github.com/jashkenas/coffee-script/wiki/Web-
framewor...](https://github.com/jashkenas/coffee-script/wiki/Web-framework-
plugins)

~~~
sehrope
There was some slight formatting issues but overall it worked well. It's nice
to have the additional context/detail with the slides kind of like what you'd
get if someone presented it live.

The node.js side project is a RESTful API so all the CS is server code (no
front end CS or JS). It all builds automatically and no special config there.
I started if off using a stripped down version of the template I linked to
above (though removing mongoose and using node-postgres async instead).

The custom build process is for out main app JackDB[1]. It's written in Java
and it's a combination of taglibs and a build script. We have a check in there
for dev/prod to decide whether to serve precompiled JS files or the original
CS files (if its local dev). We did it this way so it fits into our nginx
caching setup which marks all static assets as permanently cached (max-age +
public). The build process also prefixes the resources with the git revision
so each new build forces the client to get the latest and greatest.

[1]: [http://www.jackdb.com/](http://www.jackdb.com/)

------
benatkin
> What I find sad, though, is that most people who dislike CoffeeScript don’t
> truly know it. They haven’t taken the time to really learn it, or even try
> it. Their reactions are usually knee-jerk, or based on fallacies.

This sounds a bit like the bi-polar LISP programmer. Belief that he groks
things much better than most programmers grok things? Check. Belief that most
people are behaving irrationally? Check. Belief that it's foolish to make an
obvious choice? Check.

[http://www.lambdassociates.org/blog/bipolar.htm](http://www.lambdassociates.org/blog/bipolar.htm)

JavaScript is now a moving target. It's what the examples for new "HTML5"
features and libraries are written in. It's what an open source library should
be written in if you want it to get traction, and to attract other developers.
While it may be a good choice for quickly modifying code on a single project,
it isn't as good of a choice for something to get great in as JavaScript is.

There's the saying that you need to know JavaScript in order to write
CoffeeScript, but you really only need to be able to read JavaScript in order
to write CoffeeScript. My guess is that a lot of developers who mostly write
CoffeeScript would trip over simple things for a while if they tried switching
to JavaScript. This might keep them from seizing opportunities for JavaScript
developers such as contributing to an existing JavaScript project or an open
source library that's implemented in JavaScript.

~~~
tracker1
While I understand your sentiment... I have to disagree with a few
assumptions. I feel that it's perfectly fine to write a project, or even a
module in coffeescript. If you look at the NodeJS/NPM ecosystem, you will find
a lot of modules will use, or be used by other modules that will be in either
JS or Coffee respectively.

While CS supports some features with different syntax than JS, it really isn't
_THAT_ hard to pick up, and for the most part I don't care too much. I've
mostly written JS, but have used CS for certain bits.. I find the syntax much
more pleasant in unit testing, and for grunt tasks in particular (though will
likely be using gulp in the future over grunt).

This presentation did show a lot of the niceties with dealing in Classes with
CoffeeScript, a lot of which I wasn't aware of... I do tend to keep my objects
a bit differently than many though.. I tend to treat my objects as either
libraries or effective structures, rarely do I add "smart" methods to my
entities.

Will it get me to switch everything, no.. however, multiline strings are
nearly enough to get me to strongly consider .coffee for a lot of cases, often
I will even mix into .js projects in node.

~~~
batiste
"If you look at the NodeJS/NPM ecosystem, you will find a lot of modules will
use, or be used by other modules that will be in either JS or Coffee
respectively"

The big thing for me with Node.js was you could have whole application in one
language. Apparently it's not possible anymore because you have to deal with
CoffeScript.

~~~
tracker1
If it's a third party module, what do you care... plenty of 3rd party modules
are written as wrappers to libraries in C. Probably in your language of choice
even. This includes .Net and Java.

------
jashkenas
It's funny to see some of the comments on this thread (or the comments on any
thread about CoffeeScript), demonstrating _exactly_ what Aseem is writing in
his post. Delicious irony, that.

To make a different point, and one which can easily get missed -- the other
unsatisfactory argument I hear somewhat often is: "I love the idea of
CoffeeScript, except for X feature, which is terrible, so I won't try it."
Where X can stand for scoping, classes, optional parentheses, and the like...

One of the big goals with the CoffeeScript compiler -- despite all of it's
flaws and imperfections -- was to annotate and make accessible the source
code, and to keep it tiny (I think still somewhere ~< 2,000 LOC), so that if
there's one particular thing you don't like, you're free to change it. So if
you're intrigued, but dislike X, feel free to fix X before using it, and send
your patch along as a pull request. Open source, right?

[http://coffeescript.org/documentation/docs/grammar.html#sect...](http://coffeescript.org/documentation/docs/grammar.html#section-16)

------
nsmartt
I mostly enjoyed the slides, and I'm interested in CoffeeScript, especially
since I'm going to be working a little in Node in the near future. This post
is a critique on the blog post, rather than on the slide content, which was
more or less fine.

Too much focus placed on how those who dislike it haven't given it a proper
shot. This could be true, but six paragraphs is overkill. You make a few
points: A) they aren't being open-minded enough, B) they are the typical blub
programmer, and C) they shouldn't feel bad because it's perfectly
understandable to do something so mundane. Had I been someone who had spent a
few hours toying with CS and left unconvinced, you'd have lost me pretty
quickly.

You mention that you hated it too, at first, but not early enough. I'd submit
that you're far more likely to lose readership than to open eyes with this
method.

Also, as someone who isn't particularly set against CS, I didn't enjoy reading
so much about how I shouldn't feel bad for hating CS at first sight. I didn't.

~~~
ww520
Sounds like the OP has to justify his large mental investment he made in CS by
bashing others who have different opinions. "I'm not a blub like them. I'm not
close-minded like them. I'm not doing mundane things like them."

It's a telling sign about a language when the language advocates have to
employed negative psychological ploys to convince people (or convince
themselves) to use the language.

~~~
nsmartt
On the contrary, it seems that OP was going out of his way to explain that
it's acceptable to have initially hated CS.

If CS is actually terrible, why don't we talk about what actually makes it
terrible? I can't comprehend the notion that evaluating the advocates of X
will demonstrate anything concrete about X.

------
bentlegen
Why does everybody compare CoffeeScript against vanilla JavaScript? I find
using underscore makes my code sufficiently elegant that I've never felt the
need to switch to CoffeeScript.

~~~
tlrobinson

        var newArray = _.map(_.filter(array, function(item) {
            return item % 2;
        }), function(item) {
            return item + 1;
        });
    

vs

    
    
        newArray = (item + 1 for item in array when item % 2)
    

Uh huh.

~~~
oftenwrong
You could also do it with _chain_ , which could make the first example a bit
simpler to read and write. It is something like:

    
    
        var newArray = _.chain(array).filter(function(item) {
                return item % 2;
            }).map(function(item) {
                return item + 1;
            }).value();
    

I often use CoffeeScript + Underscore

~~~
bentlegen
You don't even need to call _.chain or value – underscore already does this
automatically. You can also write it like so, if you like:

    
    
      var newArray = _(array).filter(function(item) {
            return item % 2;
        }).map(function(item) {
            return item + 1;
        });
    

Personally, I find this quite readable. And honestly, my comment was more
about comparing CoffeeScript to its compiled JavaScript output, as is done in
the slides. The compiled output is incredibly verbose and gives the false
impression that JavaScript is always complicated.

------
ceronman
> Indeed, I, too, dismissed CoffeeScript when I first saw it. But now that
> I’ve actually learned it and used it, I see how wrong I was: CoffeeScript
> truly is more powerful than JavaScript.

My experience was exactly the opposite. When I first saw CoffeeScript, I loved
it, I started using it in my projects, it was really nice. But once I learned
to use it, I stepped into all the annoyances caused by a bad use of
significant whitespace, the many ways of doing the same thing, the tooling
overhead, and the lack of readability.

In the end, I realised that there was a negative balance of good and bad
things introduced by CoffeeScipt. It wasn't worth it. JS wasn't a bad language
after all, and the improvements of CS were minimal if you know JS well.

------
virtualwhys
I'm all for CS, use it daily, love it. It's absurd how much less code you have
to write compared to the generated JavaScript. Huge win for this alone.

However, TypeScript is perhaps the better long run alternative to plain,
boilerplate laden JavaScript. Bringing type safety into the mix is pretty
compelling, going to check out TS at some point.

------
chadhietala
I stopped using CS because it's going to have some issues when ES6 becomes
more of a real thing. For instance, how is CS going to handle for/of loops
when ES6 has it's own for/of loops that is slightly different. The same goes
for class and super.

There will have to be CS2 that introduces new semantics and old apps will have
to be migrated.

~~~
shardling
>There will have to be CS2 that introduces new semantics and old apps will
have to be migrated.

I'm sure there will be a new version of CS when ES6 becomes widespread, but
why would old apps need migrating? CS produces regular JS, and thus will be
100% compatible with ES6.

~~~
zalew
Actually coffee's js is currently compatible down to IE6, which the author
said is what he wants to support at this point. So unless MS were planning to
backport ES6 compatible JavaScript to the dead IE6, CoffeeScript supporting
ES6 will either change/break at some point or become a unreasonable backward-
compatibility clusterfuck (probably the former). ES6 becomes official in late
2014 so there is probably enough time for a lot of changes to happen.

~~~
tghw
Are you saying the current JS loops will stop working at that point? Of course
not. So why would it matter? CoffeeScript -> Javascript will continue to work
like it always did.

~~~
zalew
current js loops for sure will not, but I guess maintaining full backward
compatibility would be a hard task, so I assume at some point CS will evolve
to support only the newer standards. ie6 compatibility it's something jeremy
talks about in the podcast I linked in the other comment here.

------
fordi
It would have been great if he had mentioned IcedCoffeeScript at some point
too. Coffeescript by itself is 'ok' but IcedCoffeScript - at least on the
serverside - is fantastic.

~~~
aseemk
Indeed! I have much respect for Max and company. We use and love Streamline.js
ourselves -- works great with CoffeeScript.

[https://github.com/Sage/streamlinejs](https://github.com/Sage/streamlinejs)

I'd love to talk on or write about Streamline at some point too.

------
sergiotapia
Is CoffeeScript used much outside of Rails? If not, wouldn't it be a better
idea to focus on mastering javascript so it applies globally?

~~~
cuttooth
The presentation is very well put together, but CoffeeScript is a hack built
on top of JS in order to use Ruby semantics. You're correct in that it's not
really used outside of Rails, and not knowing JS proper (not that I personally
recommend using it for much more than jQuery and a couple other libraries,
when you absolutely must) poses a problem for when someone runs into the 97%
of code that is JS.

~~~
justinsteele
"Not really used outside of Rails" \- Do you have any source to back that up,
or is it simply what you've seen? I first used CoffeeScript in a Python shop,
personally.

------
agilebyte
I would just say that there are big differences between a JS `for` loop (`for
in` in CS) and an ES5 `forEach`. The fact that you are creating a new function
scope and are not returning all elements as you _might_ expect:

    
    
      arr = new Array 3
      arr.push 4
    
      ( alert el for el in arr )
    
      arr.forEach alert

------
pspeter3
My biggest issue is that the language can be ambiguous and I'm not sure how to
check what I'm compiling to without running the short cut all the time in
Sublime Text 2

~~~
tracker1
the coffee console app has a watch parameter iirc.. as do many build tools...

~~~
pspeter3
I'm not worried about the actual build step. I'm talking about that sometimes
it's hard to figure out how the CoffeeScript compiler is parsing and
generating the JavaScript

------
itsbits
for me its upto the developer to choose between JS or CS. I used CS for some
time and i liked it. But still i preferred to switch back to JS only to not to
waste my time in correcting CS syntax issues and play with JS.

------
consonants
Yes, let me learn this domain specific language for a domain specific language
so that I can learn another domain specific language whenever this one stops
trending.

~~~
pjscott
If you know Javascript, learning Coffeescript is easy. I became proficient in
Coffeescript in a few hours, and I sure don't _feel_ like a genius, so other
people can probably do the same. It's just a more convenient way of writing
Javascript, with a nicer syntax and some really pleasant features.

~~~
consonants
The issue at hand isn't whether or not it is easy or hard to learn, it's that
the rabbithole can go on forever as all language implementations will manifest
inadequacies which you will have to 1) be familiar with 2) know how to work
around.

It's an inherent phenomenon that DSLs will change and come and go at an
incredibly fast rate. I just don't find it worthwhile to write code that is
dependant on the DSL du jour and pigeonhole myself and whatever unlucky sole
has to maintain the legacy code in the future. Imagine being dumped on a
mountain of ColdFusion legacy code.

I just find it kind of absurd is all.

