Take a look at this simple code:
eat = (x) -> console.log \"nom\", x
# dog only eats every second cat
feast = (cats) -> eat cat for cat in cats when _
No need to guess, or make assumptions, about what Coffeescript
does. Just look at the compiled Javascript
. From the 'Try Coffeescript' tab:
feast = (cats) -> eat cat for cat in cats when _i % 2 == 0
produces
feast = function(cats) {
var cat, _i, _len, _results;
_results = [];
for (_i = 0, _len = cats.length; _i < _len; _i++) {
cat = cats[_i];
if (_i % 2 === 0) {
_results.push(eat(cat));
}
}
return _results;
};
...
feast = (cats) -> eat cat for cat, index in cats when index % 2 == 0
produces nearly the identical JS, differing only in that index
is used along with or in place of _i
.
feast = function(cats) {
var cat, index, _i, _len, _results;
_results = [];
for (index = _i = 0, _len = cats.length; _i < _len; index = ++_i) {
cat = cats[index];
if (index % 2 === 0) {
_results.push(eat(cat));
}
}
return _results;
};
Both work, but index
makes your intentions clearer to humans (including your future self). And as others have argued, it is good programming practice to avoid use of undocumented implementation features - unless you really need them. And if you are doing something funny, document it.