0

What's the difference between them, does the first one really run faster?

for (x in myArray) {
    document.write(myArray[x] + "<br />")
}

for (i=0; i<myArray.length; i++) { 
    document.write(myArray[i] + "<br />")
}
nobody
  • 223
  • 4
  • 5

1 Answers1

1

The x in y loop is about iterating over object's properties. It shouldn't be used to iterate over arrays. See this MDN article for more information about for .. in. Moreover, for .. in loop will not guarantee you any order in which it iterates over those properties.

The regular for loop can be used to iterate over ie. arrays. It will preserve order of elements.

kamituel
  • 30,600
  • 3
  • 71
  • 91