Skip to content

Commit cf509f0

Browse files
author
Jonas Höglund
committed
Added info about do-notation to chapter functions/parentheses.
1 parent bea47e3 commit cf509f0

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

chapters/functions/parentheses.textile

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,28 @@ h2. Solution
1212

1313
Use parentheses anyway.
1414

15+
Another alternative is to utilise the do-notation like so:
16+
{% highlight coffeescript %}
17+
notify = -> alert "Hello, user!"
18+
do notify if condition
19+
{% endhighlight %}
20+
21+
This compiles to the following JavaScript:
22+
{% highlight javascript %}
23+
var notify;
24+
notify = function() {
25+
return alert("Hello, user!");
26+
};
27+
if (condition) {
28+
notify();
29+
}
30+
{% endhiglight %}
31+
1532
h2. Discussion
1633

1734
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.
1835

1936
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.
2037

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

0 commit comments

Comments
 (0)