Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CoffeeScript compile a for loop in this way?

This piece of CoffeeScript:

for i in [1..10]
  console.log i

is compiled to:

for (i = _i = 1; _i <= 10; i = ++_i) {
  console.log(i);
}

I don't understand why it doesn't just use an i. Any ideas?

like image 489
Derek Chiang Avatar asked Jul 10 '13 07:07

Derek Chiang


People also ask

How do I use CoffeeScript in HTML?

You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file. In other cases, I've seen people use the attributes of type="coffeescript" and type="coffee" , so they might work for you as well. Save this answer.


1 Answers

I'm not very familiar with CoffeeScript, but my guess is that it is to prevent modification of the i variable within the loop.

For instance:

for i in [1..10]
  console.log i
  i = 7

might have produced this code

for (i = 1; i <= 10; ++i) {
  console.log(i);
  i = 7;
}

This obviously produces an infinite loop.

CoffeeScript's version, however, means this happens:

for (i = _i = 1; _i <= 10; i = ++_i) {
  console.log(i);
  i = 7;
}

The loop is no longer infinite because of the presence of _i to track the position in the loop.

like image 88
lonesomeday Avatar answered Oct 02 '22 20:10

lonesomeday