1

I'd like to do the same thing using several strings. I'd like to do it like this:

names = ["NOTE", "REPLICA", "HINT", "VIEW"];
for (name in names) {
    name = names[name];
    //do stuff
}

Then I read this. Is it still OK?

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
technillogue
  • 1,482
  • 3
  • 16
  • 27
  • If it works as expected in all environments you want to use it in, then it's OK. – Jimmie Lin Jul 17 '13 at 00:24
  • 1
    The key is here: _"`for..in` loops through the enumerable property names of an object, not the indexes of an array"_. So a `for` loop is better. Using `for..in` to loop arrays is not considered good practice. – elclanrs Jul 17 '13 at 00:26
  • I'm going to pass module along to work in environments unknown. – technillogue Jul 17 '13 at 00:28
  • Find detailed answer here, http://stackoverflow.com/a/3010848/163585 – spats Jul 17 '13 at 00:47

2 Answers2

1

It's better to go through an array using a number:

var i = 0;
for(i=0;i<names.length;i++){
 ...
}

the article you link to already mentioned that any other object properties including stuff on Array.prototype or Object.prototype will show up in for ... in another reason not to use it is that for .. in for Array's is slower.

That article does mention an edge case where for ... in could be faster when the lenght of the array is big but only a couple of items are set. In that case I guess you can use for ... in with hasOwnProperty and checking if the property is a number:

var stuff, index;
stuff = [];
stuff[0] = "zero";
stuff[9999] = "nine thousand nine hundred and ninety-nine";
stuff.name = "foo";
for (index in stuff)
{
    if (stuff.hasOwnProperty(index) && String(Number(index)) === index) {
        console.log("stuff[" + index + "] = " + stuff[index]);
    }
}
HMR
  • 37,593
  • 24
  • 91
  • 160
0

It's a lot slower than just using a for loop.

Around 86% slower in my browser (Google Chrome 28.0.1500.72).

Check out this benchmark I made.
While for..in loops only ran at 110,772 ops/sec (still fast), for loops ran at 791,792 ops/sec

I typically use for..in loops with objects. I believe that's what they are actually for.

Shawn31313
  • 5,978
  • 4
  • 38
  • 80
  • Operations per second is not the metric you should be looking at. A *for* loop will iterate once for each integer from 0 to *length*, a *for..in* loop will only iterate once for each enumerable property, which is potentially thousands fewer operations. – RobG Jul 17 '13 at 01:09