Categories
JavaScript Answers

How to Loop Over All Array Entries in JavaScript?

Spread the love

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);
});

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]);
}

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]);
}

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);
}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *