exhtml
2/16/2018 - 6:13 AM

for / forEach / for...in , What's best?

Ways of looping through Arrays in ES5:

let array = [1,2,3];

Clasic for loop

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

Array.forEach method

array.forEach(function (value) {
  console.log(value);
});

Downsides:

  • You can’t break out of this loop using a break statement or move to the next iteration with continue.

  • You can’t return from the enclosing function using a return statement.

For In

The for-in loop is designed for iterating over an objects properties, like so:

var obj = {a:1,b:2};
for (let prop in obj) {
    console.log(prop); //prints a, b
}

If we tried to use it with an array:

let array = [10,20,30];
for (let index in array) {
  console.log(index); // prints '0', '1' ... converts the index to a string
});

To iterate over key / values of an object:

for (var key in optionsDocumentTypes) {
  if (optionsDocumentTypes.hasOwnProperty(key)) {
    console.log(key + " : " + optionsDocumentTypes[key]);
  }
}

In ES6 we have a new syntax:

For Of

The for–of loop is for looping over the values in an array. It also works on most array-like objects including the new Set and Map types.

let array = [10,20,30];
for (var value of array) {
  console.log(value); // prints 10, 20, 30
}
  • This is the most concise way of looping through array elements.
  • It avoids all the pitfalls of for–in.
  • It works with break, continue, and return