2

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?

  • And why it isn't the standard in plain javascript? Is it a thing that "should is that way but we're just lazy"? –  Mar 23 '16 at 13:11

1 Answers1

1

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.

Community
  • 1
  • 1
Aleph Aleph
  • 5,215
  • 2
  • 13
  • 28
  • Ooooh, everything's clear, thank you. Now I understand why if I compile from js to cf, `for` becomes `while` :D –  Mar 23 '16 at 13:53