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 _i % 2 == 0
feast ["tabby cat"
"siamese cat"
"norwegian forest cat"
"feral cat"
"american bobtail"
"manx"]
$ coffee a.coffee
nom tabby cat
nom norwegian forest cat
nom american bobtail
It seems the _i
variable is the current index. Is this a feature, bug, or NaN? I haven't heard anyone else talking about this, so I wonder if there's some reason I shouldn't use it in my code?
No need to guess, or make assumptions, about what
Coffeescript
does. Just look at the compiledJavascript
. From the 'Try Coffeescript' tab:produces
...
produces nearly the identical JS, differing only in that
index
is used along with or in place of_i
.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.tldr-again; The author of CoffeeScript just told me I'm right: Don't use
_i
.tldr; This is at best an undocumented feature for which a functionally equivalent documented feature exists. As such, it should not be used.
Your argument of "less typing" is highly dubious; compare:
None of these things; it's undefined behaviour. You are assuming that
_i
will be the variable used for iteration in the compiled JavaScript.You definitely shouldn't use
_i
, or assume_i
will be defined. That's an implementation detail, and they're free to change it at any time. It's also won't be_i
if your loop is nested in another loop; it will be_j
or_k
etc.Most importantly, you can do this exact thing without relying on the underlying implementation's JavaSript variables. If you want to loop with an index, just use
for value,key in array
:Specifically, in your example: