Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is CoffeScript not "reusing" loop variable?

I am new to CoffeeScript and very excited about it. I made some basic loops here. Now, CoffeeScript is defining a loop variable for every loop there is as follows:

var food, _i, _j, _len, _len1;

for (_i = 0, _len = fruits.length; _i < _len; _i++) {
  food = fruits[_i];
  console.log(food);
}

for (_j = 0, _len1 = vegetables.length; _j < _len1; _j++) {
  food = vegetables[_j];
  console.log(food);
}

I used to code my loops like this:

for(var i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

for(var i = 0; i < vegetables.length; i++) {
    console.log(vegetables[i]);
}

i was my loop variable for every loop (nested loops excluded). Now I learned that you should always declare your variables before defining it. So I changed my coding habits to:

var i;
for(i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

for(i = 0; i < vegetables.length; i++) {
    console.log(vegetables[i]);
}

As long as I am in the same scope I did not see anything wrong with it, but the compiled CoffeeScript code left me wondering.

Why would CoffeeScript use a different variable for every loop?

like image 221
Amberlamps Avatar asked Feb 28 '26 20:02

Amberlamps


1 Answers

Without having looked at the CoffeeScript source code, here's my (educated) guess:

The CoffeeScript interpreter simply creates a new for loop construct for every for .. in you write. While constructing output JS, it maintains a table of local variable names and appends to that as necessary.

After all, you could nest these for .. in loops, in which case you'd start to need separate loop variables in JS anyway.

It would be necessary to track which variables in a local function scope could be potentially re-used. This is possible, but more complex than it's worth - it simply does not provide any benefit, so CoffeeScript does not do it.

like image 68
Tomalak Avatar answered Mar 02 '26 08:03

Tomalak