
CoffeeScript: JavaScript without the Fail (slides) - TrevorBurnham
http://bodil.github.com/coffeescript/
======
jameskilton
To be fair, one shouldn't bash Brendan, he had to build the initial JavaScript
language in a week[1]. It's not his fault the language became the defacto web-
language.

[1][http://www.jwz.org/blog/2010/10/every-day-i-learn-
something-...](http://www.jwz.org/blog/2010/10/every-day-i-learn-something-
new-and-stupid/#comment-1021)

~~~
dasil003
Yes, if there's one thing that Doug Crockford should have taught us all by
now, it's that Brendan was actually pretty smart, and we were damn lucky to
end up with Javascript compared to what could have been.

~~~
mixmastamyk
I don't know.... If it was really bad, it could have been replaced with
something better. If it was really good it could be kept. Today we're stuck
with something half bad/half good, we're keeping it and it is uncomfortable at
times. Add it to the deficiencies of html and css and web dev becomes a chore.

~~~
mmahemoff
We probably would have ended up with more Java and Flash.

------
thezilch
Every time I'm left unconvinced, either by pointy-edged syntax or not fair
representations of javascript...

Arrays could use a beard or the varied language syntax is going to cause
ingrown pains:

    
    
      Declaring arrays
        In CoffeeScript:
          things_that_rule = [
            "robot unicorns"
            "honey badgers"
            "Lord Inglip"
          ]
    
      Destructuring assignment
        Assign variables from inside arrays:
          sum_and_difference = (a, b) -> [a + b, a - b]
          [sum, difference] = sum_and_difference 5, 2
    

It's also bizarre from a Python background:

    
    
      >>> [
      ... "a"
      ... "b"
      ... "c"
      ... ]
      ['abc']
    

=====

    
    
      if foo.bar? then console.log foo.bar
      # if (foo.bar != null) { ... }
    

versus

    
    
      if(foo.bar){console.log(foo.bar);}

~~~
shazow
I don't understand why this is downvoted. Does somebody disagree? Why?

It's true, every time I see CoffeeScript vs JavaScript examples, they're often
unfair. Some addressed in this older thread[1].

Another thing I don't understand is why make the parenthesis for function
calls optional? Such as

    
    
        sum_and_difference 5, 2
    

Especially since one of the most common complaints about JavaScript is
ambiguous inconsistency (var, semicolons).

Ok, so parenthesis are optional,

    
    
        foo = myfunction()
    

calls myfunction, but

    
    
        foo = myfunction
    

does not? I suppose this is better than the way Ruby does it where you have to
jump through hoops to get a reference to your function, but is this really
better than making parenthesis for calls mandatory?

[1] <http://news.ycombinator.com/item?id=2542492>

~~~
grayrest
The optional parens is something I personally go back and forth on. I went
through a phase where I always left them off but have been moving back towards
using them most of the time. The holdout is for calling things that take
functional arguments. Here's how I'd write the nodejs.org home page example:

    
    
        {createServer} = require 'http'
    
        host = '127.0.0.1'
        port = 1337
    
        server = createServer (req, res) ->
            res.writeHead(200, 'Content-Type': 'text/plain')
            res.end('Hello World\n')
        server.listen(host, port)
    
        console.log "Server running at http://#{host}:#{port}/"
    

Notice `require` looks sort of like a language statement. The `console.log`
thing is my own quirk. However, the call to `createServer` would require a
hanging paren if parens weren't optional. It wouldn't look bad here (and, in
fact the official example uses it to chain the listen call) but is less
attractive if you're using longer functions. Calls like `memoize` and
`operation` (think unit of work pattern) tend to work well with this.

~~~
shazow
Perhaps I'm crazy but I honestly feel mandatory parenthesis here improve
readability

    
    
        {createServer} = require 'http'
        {createServer} = require('http')
    
        console.log "Server running at http://#{host}:#{port}/"
        console.log("Server running at http://#{host}:#{port}/")
    

At the very least, it improves consistency which to me improves readability.
Making something "look like language" (or perhaps "prose" is more appropriate)
doesn't improve the parsing process for my brain. In fact, the inconsistency
with the rest of the non-language "code" throws it off the tracks.

Even if it didn't, I'd still say the ambiguity is not worth it. Perhaps
CoffeeScript needs a "use strict"; for the final stroke of irony.

One more question: Why "#{foo}"?

Is there any template language that uses this syntax? (I am not familiar with
one.) If it were up to me, I would have chosen "${foo}" to be like Mako, or
plain "{foo}" to be like Python's string formatter, or "{{foo}}" to be like
the more recently popular Mustache.

Edit: As cschep points out, the "#{foo}" syntax is Ruby string formatting
syntax. Thanks.

~~~
cschep
Ruby does string formatting that way.

------
CJefferson
Out of interest, how does coffeescript scale, and can it start to get
unreadable?

I worry the compression, while cute, could start to get a little extreme after
a while, for example:

class Shape

    
    
      constructor: (@x, @y) ->
    
      centre: -> [ @x, @y ]
    
      area: -> 0
    

is starting to look close to unreadable and overcompressed (in particular, the
constructor implicitly declaring member variables).

Also having a quick look through the bug reports, there seems to be some
interesting inconsistencies, such as:

x for x in [1,2,3] # x == 3

x for x in [1..3] # x == 4

I also see a complaint that:

foo bar: 'baz', quux('onoz')

Won't parse. I understand this should parse as:

foo({bar:'baz'}, quux('onoz'))

Both of these, and other little things I've seen, make me think coffeescript
is more of a giant bag of good ideas, rather than a well-thought out language.
In particular, is there a clear unambiguous grammar for it anywhere? I can't
find one.

~~~
grayrest
> Out of interest, how does coffeescript scale, and can it start to get
> unreadable?

It works well enough if your API design fits the language's expectations. This
generally means your function calls take arguments in the order: normal args,
onlyOneObject, callback.

How well it scales is sort of a taste question. I like that getters/setters
and some event handlers tend to be one line. Here's a pair of functions I
actually wrote today (I'm building a proprietary wysiwyg text editor that
isn't using contentEditable)

    
    
        getBlocks: -> @_breakText(block.get('value'), block.getLineBreaks()) for block in @blocks
    
        getSelection: -> try start: @input.selectionStart, end: @input.selectionEnd
    

Here's a random longer function:

    
    
        _getWords: ->
            if @words.length
                @words
            else
                @_doWrap()
                words = []
                pos = 0
                size = 0
                Y.all(@wrapSelector).each (el) ->
                    size = el.get('text').length
                    pos  += size
                    r = el.get 'region'
                    words.push el: el
                               size: size
                               pos: pos
                               top: r.top
                               left: r.left
                               right: r.right
                               bottom: r.bottom
                @words = words
    

You'll either think these are neat or that they're horrible. Note that the
first is a comprehension and the second is a try/catch block returning an
object (it can fail in some older gecko browsers if the page is still
loading).

> in particular, the constructor implicitly declaring member variables

I think this is excessively cute as well and don't use it. Nor do I use the `x
= {a, b}` producing `x = {a:a, b:b}` trick, which causes problems with
implicit object parsing when the object isn't the last argument to the
function.

> In particular, is there a clear unambiguous grammar for it anywhere? I can't
> find one.

There is not and there probably won't ever be. Doing one would be complicated
quite a bit by the rewriting pass that happens before the compiler starts
working on the code. A grammar for the resulting, unambiguous code wouldn't be
too hard but that comes from the rewriter handling most of the hard corner
cases.

~~~
bergie
I've started preferring returning early instead of if-else. So:

    
    
      _getWords: ->
         return @words if @words.length
         # the other case of the method
    

this approach makes the code read almost like English.

------
josteink
I hope this submission doesn't signal an era of meme-worship here on Hacker
News. "Fail" may just be borderline, but it sure triggers my radar.

The flood of memes slid slowly in the back-door at reddit, one innocent step
at a time. Questioning this often got you the comment that you were old, stiff
and lacked the funny-gene. Time passed and look at what a worthless trollhole
reddit eventually became.

I hope to see fewer submissions like this on HN in the future.

------
lightcatcher
Does anyone else prefer the syntax of javascript to that of coffee script?
Really, my only problems with javascript are no multi-line strings and type
coercion (but type coercion issues are mitigated by always using ===).
Otherwise, I think javascript is a fine language. Also, the with statement
isn't that bad in my opinion.

~~~
hackinthebochs
I'm with you on that one. The only thing I feel that really needs improvement
in javascript is the long-winded lambda syntax, seeing as they're used so
much. Everything else I'm perfectly fine with. Honestly, most of what
coffeescript brings is fewer keystrokes, at the cost of ambiguity. I don't see
the purpose.

And I'm sorry, but whitespace-for-blocks really kills it for me. I can't stand
it in python, but I'll suffer through it for the ecosystem. Coffeescript
brings nothing to the table for me.

~~~
cageface
Significant whitespace is a big turn off for me too. What you gain in
concision for small examples you more than lose in tooling and code
manipulation.

~~~
simpsond
I used the think the exact same thing. However, after spending some time with
tools that do consider white space significant (coffeescript, haml, sass) I
have come to prefer it. It's part noise reduction and part consistency between
devs and environments that I prefer.

~~~
cageface
I've been burned many, many times in python by the indentation.

------
wccrawford
The slides you can type in are quite annoying. I didn't find any way to
continue other than clicking with my mouse.

~~~
fdb
I like the fact that there's a very low-barrier to entry of trying out the
language while you're learning about it. This makes the material "stick" much
better than just arrow-keying through a presentation.

I agree that the interaction could be better, though.

------
seanalltogether
The Hyperbole is strong with this one

------
rjd
Am I the only one who is amused by the irony of these guys?

i.e. "lets use Javascript end to end", and then the very same people go and
create a new language to replace said Javascript?

~~~
TrevorBurnham
I think JavaScript gets many things right, but has an overly verbose syntax.
So CoffeeScript hits a sweet spot by adding syntactic sugar while hewing close
to the underlying language.

You and Alanis Morissette may call that ironic. I'd call it practical.

------
tjholowaychuk
There's still plenty of fail, just different kinds of fail.

------
harel
Perhaps I'm missing the point here, but I don't get why there's such a hype
over CoffeeScript. People seem to prefer learning a brand new language in
order to avoid getting proficient in another language they already (should)
know. Or in other words, people prefer to learn a language that will code
another language for them. Its like I'll go and learn Japanese just so I can
use it to write phonetic English.

~~~
Bodil
In the case of CoffeeScript, the appeal, in my mind, is that it's _not_ a
brand new language, it's just an improved syntax and some extra language
features over what is essentially plain old JavaScript. Anyone who already
grasps the fundamental concepts of JavaScript can master CoffeeScript in a
matter of hours. Of course, the syntax is a matter of taste, and one might
prefer something like JavaScript 1.8, which comes with the same new language
features as CoffeeScript, and more. But some of us (and I suspect we come
mostly from Python and Ruby) prefer the concise syntax of CoffeeScript over
all those curly braces and semicolons.

~~~
harel
Well, its true the syntax of CoffeeScript is trivial, and coming from Python
background myself I find it very easy to comprehend. But I also find
Javascript fairly easy to work with and to be honest I rather work on my
target language without the abstraction of another (at least in the case of
JavaScript). Take the javascript issues covered in the presentation - they are
not hard to work with as long as you treat them as part of the Javascript
package (for example, var your local variables to make them local. not hard to
make into a habit).

------
artursapek
The beard slide made me laugh, but it doesn't hold any water. Ryan Dahl is
clean-shaven in the node.js intro video on their website. Also, I think
Javascript is great. Its 'bloated' syntax makes for minimize-able files which
can end up being half the size of the originals. That's just a preference
thing.

~~~
guywithabike
That makes no sense. If having bloated syntax is good, why not just go all out
with it?

    
    
        createafunctionwiththesearguments() {...}
    

Your reasoning makes no sense to me.

~~~
artursapek
Maybe I misunderstood, but he said Coffescript's significant indentation
solves Javascript's bloated syntax. I was just saying that code that uses
significant indentation can't be minimized, as JS files often are.
<http://bodil.github.com/coffeescript/#compress-slide>

~~~
alttab
Doesn't matter either way. If you are in a production environment, using
coffee-script would almost always involve a one-time compilation step to
minified JS.

If you are sending real users coffee-script over the wire you are wasting a
lot of their attention.

------
samgro
I love the facial hair theory. LOL.

~~~
shazow
That was cute, except Jeremy Ashkenas doesn't have a beard either. Why replace
one beardless man's language with another's?

------
reustle
What's with the biased JS examples in the beginning?

------
samrat
Will I be able to use Coffeescript with frameworks like Node.js? If yes, then
how so?

~~~
kasmura
Pedro Teixeira has made a screencast about Coffeescript in Node.js on his
website notetuts.com: [http://nodetuts.com/tutorials/16-introduction-to-
coffeescrip...](http://nodetuts.com/tutorials/16-introduction-to-coffeescript-
and-nodejs.html#video)

------
minikomi
Sorry if I'm late to the game but I have to say I started using vim-
coffeescript with coffeecompile on watch mode and it's wonderful. It's
basically like the window on the homepage but in vim.

------
yannis
Why are the slides not using coffeescript?

