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

Recommend

Implementation of Vue large file upload and breakpoint resumable upload

Table of contents 2 solutions for file upload Bas...

MySQL 5.7.21 installation and configuration tutorial

The simple installation configuration of mysql5.7...

Nginx location matching rule example

1. Grammar location [=|~|~*|^~|@] /uri/ { ... } 2...

Detailed explanation of server-id example in MySQL master-slave synchronization

Preface When we build a MySQL cluster, we natural...

How to run sudo command without entering password in Linux

The sudo command allows a trusted user to run a p...

Detailed explanation of Vue's custom event content distribution

1. This is a bit complicated to understand, I hop...

How Database SQL SELECT Queries Work

As Web developers, although we are not profession...

How to manually scroll logs in Linux system

Log rotation is a very common function on Linux s...

Example of stars for CSS rating effect

What? What star coat? Well, let’s look at the pic...

Solution to 2059 error when connecting Navicat to MySQL

Recently, when I was learning Django, I needed to...

React's component collaborative use implementation

Table of contents Nesting Parent-child component ...

A brief introduction to React

Table of contents 1. CDN introduction 1.1 react (...

Centos7.3 automatically starts or executes specified commands when booting

In centos7, the permissions of the /etc/rc.d/rc.l...