DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

How to Loop Over All Array Entries in JavaScript?

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

Looping over all array entries is a common operation we do in JavaScript programs.

In this article, we’ll look at how to loop over all entries in a JavaScript array.

Array.prototype.forEach

We can use a JavaScript instance's forEach method to loop through each entry of a JavaScript array.

For instance, we can write:

const a = ["a", "b", "c"];
a.forEach((entry) => {
  console.log(entry);
});
Enter fullscreen mode Exit fullscreen mode

We call forEach on a with a callback that gets the array entry from the first parameter.

Then we can do whatever we want with it in the callback.

for Loop

We can use a for loop to loop through all the items in a JavaScript array.

For instance, we can write:

const a = ["a", "b", "c"];
for (let index = 0; index < a.length; index++) {
  console.log(a[index]);
}
Enter fullscreen mode Exit fullscreen mode

We set index to 0, and we set the max loop limit to a.length .

And we increment index by 1 in each iteration with index++ .

Then in the loop body, we log a[index] to get the value of the a array entry with the given index .

Also, we can loop backward with:

const a = ["a", "b", "c"];
for (let index = a.length - 1; index >= 0; --index) {
  console.log(a[index]);
}
Enter fullscreen mode Exit fullscreen mode

We start with a.length , end the loop when index is 0, and we decrement index by 1 in each iteration.

The loop body is the same.

for-of Loop

Since ES6, we can use the for-of loop to loop through each array entry in our JavaScript code.

For instance, we can write:

const a = ["a", "b", "c"];
for (const val of a) {
  console.log(val);
}
Enter fullscreen mode Exit fullscreen mode

val has the value we’re iterating through.

a is the array.

The for-of loop works with any iterable object like maps and sets in addition to arrays.

Conclusion

We can loop through arrays with forEach , for loop, and for-of loop with JavaScript.

Top comments (0)