John Wang
John Wang

Reputation: 4692

Coffeescript whitespace between function name and left parenthese

What sense does the whitespace between a function name and the left parenthese make?

foo=(x,y)->x*y
foo(1,2) # ok
foo (1,2) # not ok

The last line above gives an error: unexpected , .

Upvotes: 0

Views: 91

Answers (1)

caffeinated.tech
caffeinated.tech

Reputation: 6548

In Coffeescript you can invoke a function which takes arguments with or without parenthesis:

foo(1,2)
foo 1, 2

If you have a space, then it well interpret whatever follows on the same line as the arguments. Let's take the example of another function bar which only takes one argument:

bar = (x) -> x * x

You could call this with a space before the parenthesis:

bar (2)
# ---> 4

This is because the parenthesis in Coffeescript (or Javascript) can be used to wrap an expression as well as invoke a function. Common examples are in if statements or for complex conditional / mathematical expressions. In the case of bar (2), the contents of the expression are evaluated simply to 2 (same as if you typed 2 into a coffee CLI). This is then passed to bar as if you called bar 2.

For your function foo which takes two arguments, it evaluates (1,2) as an expression. But , is not a valid operator so it throws an error. Same as if you typed 1,2 into a coffee CLI.

Upvotes: 1

Related Questions