CoffeeScript: The beautiful way to write JavaScript
amix.dk
amix.dk
I understand that syntax may be more convenient for some, but this is indirection, and is a source of complexity that may impede collaboration from other devs more familiar with JavaScript.
Every single time you see JavaScript prototypes used effectively, you'll find that they follow a classical pattern: A constructor function serves as the class object from which new objects are instantiated. Syntax like instanceof ("object instanceof class") gives this away. So do all of the built-in JavaScript classes: String, Function, RegExp, Number...
If it's an abstract object that defines common properties for instances, it's a class object, regardless of what you choose to call it. JS prototypes just expose the implementation mechanism, and CoffeeScript just provides you with a convenient way to manipulate the prototype chain.
Add to this the fact that JavaScript's prototype system isn't actually very flexible, and you're almost always better off to roll a class-based system on top of it.
In fact, Brendan Eich has taken a bunch of it's features and they will be included in the next version of JS (woot!): http://brendaneich.com/2011/01/harmony-of-my-dreams/
A function that does nothing useful but illustrates some pain points:
function frob(obj) {
var rest = [].slice.call(arguments, 1)
, results = []
for (var k in obj) if (obj.hasOwnProperty(k)) {
v = obj[k]
if (blurgh(v, rest)) {
results.push(v)
}
}
return results
}
This is roughly the same function in CS: frob = (obj, rest...) -> [v for v of obj if blurgh(v, rest)]
That's at least 5x more expressive. And it works in browsers, node, and pretty much every other JS environment. I don't write CS but you have to be blind to deny its benefits.edited: Fixed the CS to iterate over keys of obj using 'of' based on other comments here
Nitpicking aside, I totally agree about the expressiveness. I find myself writing about half the number of lines in CS as compared to JS, and the syntax fits my brain better.
frob = (obj, rest...) -> v for v of obj when blurgh(v, rest)
edit: parens dropped for noise reductionI'm wondering why I find this so annoying though. It's not like I complain about having to put parentheses in math to make sure stuff is evaluated with the precedence I want.
foo bar baz 2 # is foo(bar(baz(2)))
foo bar baz(), 2 # is foo(bar(baz(),2))
foo bar().baz 2 # is foo(bar().baz(2))
In every case, the foo is the last item on the line. In the second there's an argument after the call to baz() so it's not the last thing on the line and needs parens. In the third, baz is being chained off bar so bar is not the last thing on the line and needs parens. In general I'd do all the parens except maybe the ones for foo in the second and third cases simply because it takes a minute to figure out where the calls get split when you re-read the code.I tend to drop the call parens in situations the following:
# DSLish things
task 'foo', depends: ['bar']
# Callback/lambda taking things
xhr_get url, ->
stop_animation()
That actually covers a fairly wide set of use cases for me since I tend to write DSLish/callback code but for things like `add(2,2)` I write in the parens regardless of position.One particular example that changed everything for me was the natural and simple way I could build the typical callback constructs with -> and => , so they almost look like blocks in ruby, and feel way more natural as a control construct, and I didnt have to stack lots of })}); and so on.
If you're rather new to something, the ease of use and the simplicity and readability speeden up the learning process extremely.
That being said, there are also a couple of things in cs that are kind of silly.. like using 'for i in my_array', but 'for k of my_dict', and stuff like that, that are really hard to debug.
Although, in terms of debugging, the fact that it gets compiled and possible errors are early detected and a canonical js is generated also saved me lot of time, in particular with IE ;-)
"for item in list" vs "for key, value of object" is an unfortunate necessary evil. It would be great to use the same keyword, "in", for both types of loop, but I'm afraid there's no way for us to know at compile time if "list" or "object" is really an array, or really an object.
for (var i = 0, l = list.length; i < l; i++) { ... }
And objects iterated over with: for (var key in object) { ... }
Using a "for-in" loop over a JS array isn't acceptable, for performance and semantics reasons, and neither is sniffing at runtime to determine whether the object passed is an array, or an object.Ideally, JavaScript would have supported a single iteration protocol for both arrays and objects from the get-go, but alas...
If you dont mind my asking, how would i go about using CoffeeScript with Node?
If it's more elaborated, you might want to set up some kind of build process and then use the generated js files. You could use a simple Makefile and compile your coffee files with coffee -c -b.
* In js->cs rewrites I usually wind up cutting the line count in half, but most of that is eliminating all the stray closing brackets on their own lines and collapsing if statements into single lines.
Personally I think Coffeescript is a big step forward. A pity it will likely never gain enough momentum to see native implementations on the major browsers.
I disagree with this (though I agree with the rest of your post). The people that like CoffeeScript (and StratifiedJS and other projects like ObjectiveJ) are generally people that do get JavaScript really well. They just want to make it better.
The problem with CoffeeScript and the others is that they are not JavaScript. CoffeeScript is pretty straightforward in that it hardly even looks like JS and just compiles down to it, but others pretend to be JS but introduce new structures that make them all completely different languages (and do source transformation using JS in the browser).
If you don't know the transformations and you don't know JS very well, all these languages on top of JS will leave you stranded the second something goes wrong anywhere in the stack.
I'd like to see JS adopt some core structures for concurrency, namespaces and more CommonJS stuff instead of adding let, generators and comprehensions - which are nice, but mostly just fluff because you can do all those using the core language already and they're details nobody really cares about.
JavaScript itself doesn't embrace a prototypal model. When was the last time you cloned an object to create a new one in JS?
JavaScript's model is much closer to classes than prototypes. The only real significant difference is that unlike class systems, JavaScript allows inheriting both "methods" and "state" from its "class". Otherwise, the language works more or less like a class-based one.
BEATUY IS IN THE EYE OF THE BEHOLDER people! Just because you find javascript 'ugly' and coffeescript 'beautiful' doesn't actually mean everyone agrees with you. I think Javascript is beautiful and I've been coding it for 14 years. I have no need to replace the syntax, or complicate my development tools, or make debugging any more complicated that it already is.
Coffeescript evangelists are like born-agains who try to convert every man woman or child to their newfound religion because their god is the true god. It's annoying really.
It's that simple.
Sure, the name sucks, but that's hardly an issue.
Sure, as long as you already understand Javascript. Think of people who are learning, or middle managers that are hiring. It's a lot more of a thorn than you might think, because you're educated.The biggest problem with CoffeeScript adoption is the administrative overhead required for novices to get it running. This means that most CoffeeScript projects are usually larger -- it just doesn't get used in small one-off things.
My company's product is a hosted CMS and we just tackled this problem (http://www.gethifi.com/blog/hosted-cms-coffeescript-support) by completely eliminating the workflow issue. You can use Coffee or JS and the system takes care of the rest for you.
I've found this to be a big help when working on smaller client sites. Often I just need to write a couple dozens lines of JS and it just isn't worth the hassle to do it in Coffee -- now it's gravy.
Read original here, http://jashkenas.github.com/coffee-script/
When I found CoffeeScript, I was very happy. But I've been moving back to more JavaScript recently because I've spent hours looking through the generated JavaScript and learned quite a bit from it. I did the same with my C compiler and x86 Assembly :) It's nice to read what the experts think the final product should look like.
So write some CoffeeScript, compile it, and learn some JavaScript from it.
What's with today's obsession over beautiful syntax? Shouldn't we strive for beautiful semantics, instead?
(To be clear: I don't have a strong opinion. I'm curious what the community thinks the value proposition for CoffeeScript, HAML, etc is.)
What do you mean?
(Edit: I don't think that "pretty" is a bad thing. I just... when is it the most important thing, or even high up on the priority list? Pretty isn't bad, but if it means learning an entirely new syntax and immature toolchain, its value for all but personal projects is unclear to me. I see that others value it differently, and I'm trying to understand why.)
I'd be really shocked if you showed a solid Javascript programmer who has written code in a scripting language like Perl, Python, or Ruby a chunk of CoffeeScript code and he/she couldn't easily infer what was going on just by intuition alone.
IMHO, in this instance, absolutely yes. I enjoy using CoffeeScript in a way I've never enjoyed JS. It's easier to write and easier to read. For example, compare:
x = this.x;
y = obj.map(function(z) {return z + x;});
with y = obj.map z => z + @x
I also find it of great benefit if I'm coding elsewhere in Ruby (for example, if I'm coming from some Ruby coding I'm prone to forgetting return statements in my JS at key moments).There are many, many interesting projects that I want to look at, read, potentially use or learn from.
Every little help for reading and understanding many open source projects faster is a huge value and a huge timesaver for me.
I think that clean syntax is just the better tool, like other people would probably prefer an IDE with integrated toolchain and dozens of tools that are modeled after the state of a programming system at some point in time.
Readable semantics behind a clean syntax are the more flexible toolchain in my eyes. It's like an integrated user interface. I can easily read and understand CS/Haml/Sass/Ruby/.. in my own files, in some libraries that i installed, in posts on blogs and on github ..
Personally I disagree.
I think a programming language is not like a car, at least not in that with a car whether it's pretty or not has no practical effect on the utility of the car.
You are using the computer language to express your own ideas, and to formulate your own constructs via it's syntax and semantics.
When the language's syntax and semantics are clunky, verbose, and full of line noise....those things become intermingled with your ideas and your semantics and it becomes difficult to separate the two.
I've been writing Javascript a long time, and what I like about CS is not only that it makes writing code easier by providing shortcuts for patterns I use constantly, but that the finished code more closely resembles the actual ideas I had when I wrote the code. With syntax and semantics that get out of the way you can focus more closely on your ideas and how to improve or fix them imho.
"Pretty" is great -- desirable, even. But if "pretty" comes at the cost of using immature tools that may slow me down, or at the cost of forcing my development team to learn a new syntax just because I believe it's "pretty" -- well, that's a harder value proposition.
That's what I'm trying to get at with all this. It sounds like, to you, the level of "pretty" in CoffeeScript outweighs the potential disadvantages -- which is great!
I do like the notion that CoffeeScript syntax gets out of the way; that it lays constructs and ideas bare in a way that JavaScript does not.
How long do you expect it to take your team to learn the syntax? I would expect anyone with JS experience to have this [1] page open and be able to immediately start writing code and have it down in no time.
The first is that CoffeeScript is ultimately a sort of dialect of Javascript. CS and JS can interact with eachother seamlessly, so as mentioned in the OP article there's no need to switch over to CS for everything and/or all at once.
Another important thing is that where possible CS tries to map relatively directly to JS, so for experienced JS developers they will recognize CS as a series of shortcuts which map to idioms they use constantly.
If you are familiar with JS, doing a few small projects in CS should get you pretty familiar with it.
CS is obviously somewhat immature, but I think it's reached the point where it can be considered for "serious work". I've found the tooling is pretty decent: coffee is slick with commands like --watch to recompile on changes, and coffee-mode for emacs is nice. There's also CS mode for vim, textmate, gedit, + more.
Honestly the main hurdle is potential debugging problems, but I haven't found that to be too difficult either. Being mindful of how CS transforms your code, and strategic debugging code make the process for me not much different from debugging regular JS.
So I'd say at this point I don't think CS presents hurdles which are terribly difficult to overcome.
That said, we certainly try to improve upon JS semantics, where it's possible to do so without a performance hit. Things like auto-lexical scoping, bound functions, chained comparisons and, most importantly, "everything is an expression", are all examples of this.
To be specific, the main speedup I tend to get is this: If I'm working with JS, I'll tend to use a "forEach" function frequently, for looping over lists:
list.forEach(function(item){ item.transform(); });
In CoffeeScript, you'd write it like this: item.transform() for item in list
... and instead of the slow "forEach" function, you get a much faster native "for" loop.I was writing a web server that just wouldn't compile, looked the code over several times and eventually gave up and did it in javascript instead. Later found out that Gedit was displaying a tab that vim showed as just being a space. Never tested if that was the only problem or not.
One question I had while reading this. Was there a technical reason why he didn't make a gem or toolkit in pure Ruby or Python that would then spit out Javascript?
I think this is closer to how GWT did it where you can write pure Java, and of course it then wouldn't require people to learn a new language.
For people who know JavaScript, it's not a new language-- just some syntactic sugar and a few bonus features.
http://fleetinbeing.net/raffi/ (type "spiral 30" to run a function defined in CS, then type "spiral" to see the definition in JS)