Summary of ways to loop through the arrays in JavaScript

created at March 5, 2021, 9:41 a.m.

This paper compares and summarizes four ways to iterate:

for loop:

for (const key in someArray) {
  console.log(key);
}

Array method .forEach()

someArray.forEach((elem, index) => {
  console.log(elem, index);
});

for-of loop:

for (const elem of someArray) {
  console.log(elem);
}

for-of is usually the best choice. We will illustrate why. 

for loop [ES1]

The for loop in JavaScript is very old, and it already exists in ECMAScript 1. The for loop records the index and value of each element of arr:

const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

for (let index=0; index < arr.length; index++) {
  const elem = arr[index];
  console.log(index, elem);
}

// Output:
// 0, 'a'
// 1, 'b'
// 2, 'c'

What are the advantages and disadvantages of for loops?

  • It has a wide range of uses, but it is also troublesome when we want to iterate an array.
  • It is still useful if we don't want to loop from the first array element, which is difficult to do with other loop mechanisms.

for-in loop [ES1]

The for-in loop is as old as the for loop, and it also comes in ECMAScript 1. The following code uses a for-in loop to output the key of arr:

const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

for (const key in arr) {
  console.log(key);
}

// Output:
// '0'
// '1'
// '2'
// 'prop'

for-in is not a good way to loop through an array:

  • It accesses the attribute key, not the value.
  • As an attribute key, the index of an array element is a string, not a number.
  • It accesses all enumerable property keys (own and inherited), not just those of Array elements.

The practical use of for-in access to inherited properties is to iterate all enumerable properties of an object.

Array method .forEach() [ES5]

Since neither for nor for-in is particularly suitable for looping on arrays, an auxiliary method was introduced in ECMAScript 5: Array.prototype.forEach():

const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

arr.forEach((elem, index) => {
  console.log(elem, index);
});

// Output:
// 'a', 0
// 'b', 1
// 'c', 2

This method is really convenient: it allows us to access array elements and indexes without performing a lot of operations. If you use arrow functions (introduced in ES6), the syntax will be more elegant.

The main disadvantages of .forEach() are:

  • You cannot use await in its loop body.
  • You cannot exit the .forEach() loop early. You can use break in a for loop.

The solution to abort .forEach()

If you want to abort a loop like .forEach(), there is a workaround: .some() will also loop through all array elements and stop when its callback returns a true value.

const arr = ['red', 'green', 'blue'];
arr.some((elem, index) => {
  if (index >= 2) {
    return true; // abort loop
  }
  console.log(elem);
  //This callback implicitly returns `undefined`, this
  // is a pseudo value. Therefore, the cycle continues.
});

// Output:
// 'red'
// 'green'

It can be said that this is an abuse of .some(). Compared with for-of and break, it is not easy to understand this code.

for-of loop [ES6]

For-of loops are supported in ECMAScript 6:

const arr = ['a', 'b', 'c'];
arr.prop = 'property value';

for (const elem of arr) {
  console.log(elem);
}
// Output:
// 'a'
// 'b'
// 'c'

for-of is very effective when looping through an array:

  • Used to iterate the array elements.
  • You can use await
    • If necessary, you can easily migrate to for-await-of.
  • You can even use break and continue for outer scope.

for-of and iterable objects

For-of can iterate not only arrays, but also iterable objects, such as iterating Map:

const myMap = new Map()
  .set(false, 'no')
  .set(true, 'yes')
;
for (const [key, value] of myMap) {
  console.log(key, value);
}

// Output:
// false, 'no'
// true, 'yes'

Traversing myMap will generate [key, value] pairs, which can be deconstructed to directly access each pair of data.

for-of and array indexing

The array method .entries() returns an iterable [index, value] pair. If you use for-of and use this method for destructuring, you can easily access the array index:

const arr = ['chocolate', 'vanilla', 'strawberry'];

for (const [index, elem] of arr.entries()) {
  console.log(index, elem);
}
// Output:
// 0, 'chocolate'
// 1, 'vanilla'
// 2, 'strawberry'

summary

The usability of for-of loops is better than for, for-in and .forEach().

Generally, the performance difference between the four loop mechanisms should be irrelevant. If you are doing something that is computationally intensive, it is better to switch to WebAssembly.

Please log in to leave a comment.