Why does CoffeeScript compile the for loop this way?

This piece of CoffeeScript:

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

compiled for:

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

I do not understand why it is not just using i . Any ideas?

+7
javascript coffeescript
source share
1 answer

I am not very familiar with CoffeeScript, but I assume that it should prevent the variable i from being modified in a loop.

For example:

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

could create this code

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

This obviously creates an endless loop.

The CoffeeScript version, however, means this is happening:

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

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

+11
source share

All Articles