Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CoffeeScript require whitespace after map?

Tags:

coffeescript

This code

nums = [1..10].map (i) -> i*2

Runs

Whereas this

nums = [1..10].map(i) -> i*2

is broken

like image 610
deltanovember Avatar asked Jan 26 '12 07:01

deltanovember


2 Answers

The reason for this is that parentheses for a function call (invocation) are optional. I find this a constant confusion in my own code and have a general policy of always including parentheses to make it clear.

In coffee script, if you leave out the parentheses it assumes that the argument list goes to the end of the line. Your first example coffee script is actually the same as this:

nums = [1..10].map((i) -> i*2)

where the first argument of the call to map is a function (i)->i*2

If you remove the space between the map and the (i) then coffee script implies parentheses around the rest of the line. Your second example coffee script is actually the same as this:

nums = [1..10].map(i)(-> i*2)

Here you can see that map is being called with i as the only argument and then coffee script is expecting the map(i) call to return a function which is then being called passing ->i*2 or to be more explicit ()->i*2 as an argument.

Given that coffee script is designed to remove the potential coding hazards of javascript, I think that it would have been much safer if they had not included this implied parenthesis.

like image 62
Pete BD Avatar answered Nov 09 '22 07:11

Pete BD


The map(i) in the second one is interpreted as a function call. The JavaScript comes out like this:

var nums;

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(i)(function() {
  return i * 2;
});

and that doesn't make any sense because map doesn't return a function and there is no i defined.

In the first one, the space turns it into [1..10].map((i) -> i*2) so you end up calling map with a function as an argument; the JavaScript in this case looks like this:

var nums;

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(function(i) {
  return i * 2;
});
like image 35
mu is too short Avatar answered Nov 09 '22 09:11

mu is too short