Reputation:
Was wondering why does Coffeescript works this way:
for i in [0..10]
return i
becomes
for (i = j = 0; j <= 10; i = ++j) {
return i;
}
rather than just
for (i = 0; i <= 10; i++) {
return i;
}
Is it just because of the "philosophy" about variables? The thing about security for not overwrite them?
Upvotes: 2
Views: 41
Reputation: 5395
The for ... in ...
loop in Coffeescript enables you to iterate through all elements in an array. It is guaranteed to have as many iterations as there are items in the original array, and will give you all of the array's elements in sequence (unless you modify the original array).
Try to compile
for s in ['a', 'b', 'c']
console.log s
and see the resulting Javascript output.
The i = j = 0; j <= 10; i = ++j
construction is just an optimisation done by the Coffeescript compiler to avoid literally creating the array [0..10]
- but in the same time, a change in the iteration variable should not affect the values that are further in the array.
As in Python, if you want a more complicated control flow than just iterating over all of an array's elements in sequence, you are free to use while
loops.
Plain Javascript, in its turn, seems to follow C's philosophy in regard to the for
loops - where the programmer is free to introduce any changes to do low-level optimizations.
Upvotes: 1