Day 1 of learning CoffeeScript.
I won’t lie. After I’ve spent about 30 minutes so far reading up on the documentation for CoffeeScript and my head is starting to spin.
I’m trying to decode some of the syntactic sugar that CoffeeScript provides, but even one liners are tripping me up right now:
1 |
setName = (name) -> @name = name |
really means:
1 2 3 4 5 |
var setName; setName = function(name) { return this.name = name; }; |
and what’s more confusing is that there is even shorthand for this where somehow:
1 |
setName = (@name) -> |
means this:
1 2 3 4 5 |
var setName; setName = function(name) { this.name = name; }; |
I know that there’s going to be a lot of getting used to, but so far this is just making my head dizzy.
What I like:
String interpolation
The way I think about string interpolation is string concatenation done easier (or maybe done right? does syntactic sugar mean that it’s more right?). I suspect as I learn CoffeeScript more, there are going to be more of these “that’s cool” moments.
1 2 |
string = 'world' console.log "Hello #{string}!" |
whose JavaScript equivalent is:
1 2 |
var string = 'world'; console.log("Hello " + string + "!"); |
Splats
Wow…that’s neat. When used as an argument in a function it basically is an array of values. What makes it cool is that you can surround it with variables and it’ll just slurp up all the other arguments and put it into an array.
1 2 3 4 5 |
story = (beginning, middle..., end) -> console.log beginning console.log middle.join(' ') console.log end story 'one', 'two', 'three', 'four', 'five' |
Output:
one
two three four
five
It’s like it splats together variables into an array.