I am working with coffeescript (version 1.11.1) and I ran into something that I'm struggling to describe. I was simply trying to sort an array of objects by a field, which I can do like so:
data.sort (a,b) ->
if a.name < b.name then -1 else if a.name > b.name then 1 else 0
This produces the following javascript:
data.sort(function(a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
});
Awesome. But in my first attempt I did this instead:
data.sort(a,b) ->
if a.name < b.name then -1 else if a.name > b.name then 1 else 0
And the generated javascript is for that is:
data.sort(a, b)(function() {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
});
Which, because javascript is so helpful, fails silently (at least in Chrome) and causes the surrounding function to return prematurely. A little frustrating but I'll get over it.
First I want to confirm that is expected behavior. I think it probably is and I have some vague thoughts bouncing around my skull about why it does this but I was hoping to get a firmer understanding. How should this be described or what terminology is relevant for this feature of the language?
That is the expected behaviour.
CoffeeScript supports all of the following:
(a, b) -> 5
notation for functions,
-> 5
notation for functions without arguments,
f(a, b)
notation for function calls, and
f a
notation for function calls (implicit parentheses).
So how do you call the result of a function call f(a, b)
with a function parameter -> 5
?
The answer is—
f(a, b) -> 5
—which as you've noticed, looks rather similar to—
f (a, b) -> 5
—which translates to calling f
, passing the function (a, b) -> 5
as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With