Summary of four ways to loop through an array in JS

Summary of four ways to loop through an array in JS

This article compares and summarizes four ways of traversing an array:

for loop:

for (let index=0; index < someArray.length; index++) {
 const elem = someArray[index];
 // ···
}

for-in 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'll see why.

for loop [ES1]

The for loop in JavaScript is very old, it has been around since 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 the for loop?

  • It's very versatile, but it can also be cumbersome when we want to iterate over an array.
  • It is still useful if we do not want to start the loop from the first array element, which is difficult to do with other looping mechanisms.

for-in loop [ES1]

The for-in loop is as old as the for loop, also existing 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 over an array:

  • It accesses the property keys, not the values.
  • As property keys, the indices of array elements are strings, not numbers.
  • It accesses all enumerable property keys (own and inherited), not just those of Array elements.

The actual purpose of for-in accessing inherited properties is to iterate over all enumerable properties of an object.

Array Method .forEach() [ES5]

Since neither for nor for-in are particularly suitable for looping over arrays, a helper 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 approach is really convenient: it allows us to access array elements and indices without having to perform a lot of operations. If we 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.
  • It is not possible to exit a .forEach() loop prematurely. And break can be used in for loops.

Abort .forEach() solution

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

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

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

This can be said to be an abuse of .some(), and compared to for-of and break, it is not easy to understand this code.

for-of loop [ES6]

The for-of loop is 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 at looping over arrays:

Used to iterate over array elements.

You can use await

  • If necessary, it is easy to migrate to for-await-of.

You can even use break and continue with outer scopes.

for-of and iterables

for-of can not only traverse arrays, but also iterate over iterable objects, such as 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'

Iterating over myMap generates [key, value] pairs, each of which can be accessed directly by destructuring it.

for-of and array indexing

The array method .entries() returns an iterable of [index, value] pairs. If you use for-of and destructuring with this method, 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'

Summarize

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

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

This concludes this article on the four ways to loop through an array in JS. For more information about looping through an array in JS, please search for previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to loop through all elements in a js array
  • JS array traversal method for loop and for...in
  • Summary of methods for looping through Array and Map in JavaScript
  • JS simple loop traversal json array method
  • JS uses a for loop to iterate through all the cell contents of a Table
  • JS method of looping through JSON data
  • javascript forEach general loop traversal method
  • JS uses for loop to traverse child nodes to find elements
  • 12 loop traversal methods in JavaScript [Summary]
  • Do you know all 24 methods of JavaScript loop traversal?

<<:  Detailed explanation of docker's high availability configuration

>>:  MySQL sequence AUTO_INCREMENT detailed explanation and example code

Blog    

Recommend

Two usages of iFrame tags in HTML

I have been working on a project recently - Budou...

MySQL Failover Notes: Application-Aware Design Detailed Explanation

1. Introduction As we all know, in the applicatio...

Bootstrap 3.0 study notes CSS related supplement

The main contents of this article are as follows:...

How to configure ssh to log in to Linux using git bash

1. First, generate the public key and private key...

MySQL 5.7 generated column usage example analysis

This article uses examples to illustrate the usag...

Solution to the Chinese garbled characters problem in MySQL under Ubuntu

Find the problem I have been learning Django rece...

Development details of Vue3 components

Table of contents 1. Introduction 2. Component De...

Tutorial on installing and uninstalling python3 under Centos7

1. Install Python 3 1. Install dependency package...

Detailed explanation of data type issues in JS array index detection

When I was writing a WeChat applet project, there...

Docker Gitlab+Jenkins+Harbor builds a persistent platform operation

CI/CD Overview CI workflow design Git code versio...

HTML commonly used meta encyclopedia (recommended)

The Meta tag is an auxiliary tag in the head area...

HTML blockquote tag usage and beautification

Blockquote Definition and Usage The <blockquot...

Summary of 50+ Utility Functions in JavaScript

JavaScript can do a lot of great things. This art...

Sample code for changing the color of a png image through a CSS3 filter

This method uses the drop-shadow filter in CSS3 t...