Looping over arrays in Javascript

Dear all,

there is only one correct and efficient way to loop over an array in Javascript

var arrayOfThings = [...some things...];
var nThings=arrayOfThings.length;
for (var i=0;i<nThings;i++) {
  var thing = arrayOfThings[i];
}

Using

var arrayOfThings = [...some things...];
for (var i in arrayOfThings) {
  var thing = arrayOfThings[i];
}

Is not correct (and if you are using IntelliJ it will show you a warning).

This has been written about many times, so I’ll let some other people explain

stackoverflow.com/questions/5005 … a-bad-idea

Here is some more information: Particularly interesting is the idea that if you have an indexed array and loop through it with a for…in statement then it stops being an indexed array and it can’t be optimised any more.

github.com/petkaantonov/bluebir … on-killers

Is it still the case? it was before. Curious if there are examples on jperf (haven’t read the article tho, sorry)

Yes, this is still the case. - As far as I am aware.

What I mean is that I have not seen anyone suggest that it is no longer the case.

BUT, beyond optimisation there is still the issues the for…in loops over all the properties and is not an indexed loop. It will pick up Array.prototype methods defined by V8 and any other libraries. It is not what you want to do in most cases.

Hi,

I know that in Javascript, arrays are nothing else than usual objects, and this is basically why this rule applies.
But when arrays are used for what they’re really meant to be, that is a sequential, contiguous collection of things, is the “for…in” construction still bad?

Actually, the “bad” example you show, let’s recall it:

var arrayOfThings = [...some things...];
for (var i in arrayOfThings) {
  var thing = arrayOfThings[i];
}

It doesn’t look that bad to me, because the array here is defined explicitly, it’s not mutated, it matches what I expect from an array (sequential & contiguous collection); Despite intellij’s &co warnings, is it really a good example of bad “for…in” usage? Of course we can argue that, given the construction can be sometimes safe and sometimes unsafe, it’s easier to ban it completely for convenience. But I want to see if the rule is unbreakable :slight_smile: