0

On the one hand you could write array.forEach(function(item){}) or you could write for each(let item in array){}

I'm trying to understand when it is better to use each method of looping over items in a Javascript array.

Thanks!

user1056805
  • 2,633
  • 5
  • 21
  • 19
  • 3
    `for each in` is non-standard, and deprecated in Firefox. And `let` is not yet part of the standard, though it's on its way. –  Aug 08 '13 at 19:05
  • oh ok, so I guess forEach is the more correct method then? – user1056805 Aug 08 '13 at 19:06
  • 6
    See this answer - it's got a lot of great info on each method: http://stackoverflow.com/a/9329476/870729 – random_user_name Aug 08 '13 at 19:07
  • Currently, yes. I believe there's a similar syntax coming in ECMAScript 6 called [`for-of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) –  Aug 08 '13 at 19:07
  • you can call/apply the guts of a forEach() routine from elsewhere, but for of/each/in will always be locked into the containing program. – dandavis Aug 08 '13 at 19:19
  • @dandavis: I don't understand the significance of that. The need to call/apply against `forEach()` is that it's specifically associated with Array objects via `Array.prototype`. There wouldn't be any need for that with iteration statements. –  Aug 08 '13 at 19:37
  • @CrazyTrain: what i mean, for example, function(a){this[0]+=a;} can be used from other functions, but { sum+=o[i]; } cannot... that's why loops suck unless you really need the perf benefits of a bareback for-loop, which are diminishing every 6 weeks it seems. – dandavis Aug 08 '13 at 20:16
  • @dandavis: Oh, I get what you're saying now. –  Aug 08 '13 at 20:27

0 Answers0