Defining functions
Function syntax might be the single most-talked-about feature of CoffeeScript. It's notable because it is strange: it doesn't feel familiar to a programmer coming from JavaScript (or from most other languages, for that matter). You might not like it immediately, but give it some time and you'll find it grows on you. Like a foreign language, at first you may need to pause and translate the syntax back into a familiar form. Give your brain a little time to rewire, though, and soon you'll be able to read and understand CoffeeScript instantly.
Let's look at the following example:
(name) -> return "Hello, #{name}!"
This is a simple anonymous function that takes one argument, name
, and returns a message saying hello
. If you're puzzled, let's take a look at the resulting JavaScript:
(function(name) { return "Hello, " + name + "!"; });
The arguments declaration remains the same. JavaScript's function
keyword and curly brace are replaced by a ->
. Just like the if
statements...