{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. {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.
(Although I don't know what that would be doing in a console log.)
`Require` and `console.log` are perfect examples where leaving off the parentheses helps with clarity, same with the call to `createServer`. In your example I'd even argue that you could do the same with `res.end` too.
foo = object.method(:method_name)
foo.call
foo = myfunction
Considering the higher-order nature of Javascript programming having quick access to refs is important.The Coco dialect of Coffee suggests that a bang could be used to denote a call:
foo = myfunction!
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
Especially since one of the most common complaints about JavaScript is ambiguous inconsistency (var, semicolons).Ok, so parenthesis are optional,
calls myfunction, but 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