Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion chapters/functions/parentheses.textile
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,28 @@ h2. Solution

Use parentheses anyway.

Another alternative is to utilise the do-notation like so:
{% highlight coffeescript %}
notify = -> alert "Hello, user!"
do notify if condition
{% endhighlight %}

This compiles to the following JavaScript:
{% highlight javascript %}
var notify;
notify = function() {
return alert("Hello, user!");
};
if (condition) {
notify();
}
{% endhiglight %}

h2. Discussion

Like Ruby, CoffeeScript allows you to drop parentheses to method calls. Unlike Ruby, however, CoffeeScript treats a bare function name as the pointer to the function. The practical upshot of this is that if you give no arguments to a method, CoffeeScript cannot tell if you want to call the function or use it as a reference.

Is this good or bad? It's just different. It creates an unexpected syntax case—parentheses aren't _always_ optional—but in exchange it gives you the ability to pass and receive functions fluently by name, something that's a bit klunky in Ruby.


This usage of the do-notation is a neat approach for CoffeeScript with parenphobia.
Some people simply prefer to write out the parentheses in the function call, though.