Why does CoffeeScript require a space after the map?

This code

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

Starts up

While this one

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

broken

+5
source share
2 answers

The reason for this is that parentheses for calling a function (call) are optional. I find this a constant confusion in my own code, and I always follow a common policy, including parentheses, to clarify.

In a coffee script, if you leave parentheses around, it is assumed that the argument list moves to the end of the line. Your first coffee script example is actually the same:

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

where the first argument to calling map is the function (i)->i*2

(i), script . script :

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

, i , script map(i) , ->i*2, ()->i*2 .

, script javascript, , , .

+6

map(i) . JavaScript :

var nums;

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

, map i.

[1..10].map((i) -> i*2), map ; JavaScript :

var nums;

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

All Articles