0

Suppose I want to loop through an entire array to access each element. Is it standard practice amongst JavaScript developers to use a for loop, for...in loop, or for...of loop?

For example:

var myArray = ["apples", "oranges", "pears"];

For loop

for (var index = 0; index < myArray.length; index++)
    console.log(myArray[index]);

For...in loop

for (var index in myArray)
    console.log(myArray[index]);

For...of loop

for (var element of myArray)
    console.log(element);
Chuck
  • 998
  • 8
  • 17
  • 30

2 Answers2

1

forEach should be the way to go, as part of the Array.prototype functions.

For loop

for (var index = 0; index < myArray.length; index++)
    console.log(myArray[index])

If I had to pick one of the above, vanilla for-loop with length above is the most preferred.

For...in loop

for (var index in myArray)
    console.log(myArray[index]);

You should avoid this at all cost! It's bad practice to mix idioms meant for Object with Array. You may run into buggy iterations through unwanted elements

Ling Zhong
  • 1,744
  • 14
  • 24
1

For loop

for (var index = 0; index < myArray.length; index++)
console.log(myArray[index]);

This is the best choice for an array, and crossbrowser ! It will permit to break the loop when you want, but not with a Array.forEach

For in

Avoid this approach with array !

Anonymous0day
  • 3,012
  • 1
  • 14
  • 16