3

This MDN page claims:

...you can iterate over an array using the following:

for (var i = 0; i < a.length; i++) {
  // Do something with a[i]
}

This is slightly inefficient as you are looking up the length property once every loop. An improvement is this:

for (var i = 0, len = a.length; i < len; i++) {
  // Do something with a[i]
}

A nicer-looking but limited idiom is:

for (var i = 0, item; item = a[i++];) {
  // Do something with item
}

Are these really commonly accepted ways of iteration? Wouldn't modern JavaScript engines simply optimize the first one?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • 3
    *Wouldn't modern JavaScript engines simply optimize the first one?* Yes, they would. The MDN page is wrong. Remember that MDN is written by regular people like me and you. By the way, the last fragment is horrible, because it will stop the loop on any non-falsy array element. I've fixed the MDN page. –  Mar 28 '16 at 04:01
  • 2
    As a general rule, don't do weird things because they're "faster." Write obvious code. The compiler writers will spend more time optimizing obvious code to be fast, and maintenance developers will have an easier time understanding what you were trying to do. Only do the weird contortion when you can prove it is *noticeably* faster to the *user*, not *measurably* faster to some benchmarking test. – Ian McLaird Mar 28 '16 at 04:22
  • Of course; I was confused because I assumed MDN was an authoritative source and also used the second method in many examples. – Mateen Ulhaq Mar 28 '16 at 10:02

1 Answers1

1

The MDN page is incorrect. Modern engines will optimize the handling of length. In fact, some engines will actually run the first fragment faster.