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

jQuery plugin to achieve code rain effect

This article shares the specific code of the jQue...

IDEA complete code to connect to MySQL database and perform query operations

1. Write a Mysql link setting page first package ...

In-depth analysis of the Linux kernel macro container_of

1. As mentioned above I saw this macro when I was...

Vue components dynamic components detailed explanation

Table of contents Summarize Summarize When the ar...

Analysis of the difference between absolute path and relative path in HTML

As shown in the figure: There are many files conne...

Graphical explanation of the function call of proto file in Vue

1. Compile proto Create a new proto folder under ...

How to install MySQL 5.7.17 and set the encoding to utf8 in Windows

download MySQL official download, select Windows ...

React Synthetic Events Explained

Table of contents Start by clicking the input box...

The difference and usage of datetime and timestamp in MySQL

1. How to represent the current time in MySQL? In...

Vue data responsiveness summary

Before talking about data responsiveness, we need...

Common operation commands of MySQL in Linux system

Serve: # chkconfig --list List all system service...

Introduction to the functions and usage of value and name attributes in Html

1. The value used in the button refers to the text...