How to loop over an array in JavaScript?

How to loop over an array in JavaScript?

Iva Kop

· 5 min read

There are so many different ways to loop over an array in JavaScript. Sometimes, it becomes genuinely difficult to know which method to choose for a particular use case. And even though a lot of these methods can be used interchangeably to "get the job done", knowing when and how to utilize each one makes our code more readable, maintainable and, in some cases, better optimized.

Let's create an array and explore some more common use cases:

const array = [4, 6, 8, 10, 8, 12, 6, 45, 8];

Multiply by 2

Let's start simple. Our first task is to multiply each item in our array by 2. What do we do?

If we want to create a new array with the result the easiest path is to use map:

const result = array.map((item) => item * 2);

If the goal is to mutate the original array, forEach is a good choice:

array.forEach((item) => item * 2);

Cool! Let's do another one.

Filter out 8

Here is another common task. Let's say we want to filter the number 8 out of our array. How do we go about it?

Once again, it matters whether we want to create a new array or mutate the existing one.

To create a new array with the desired result, filter is a great option:

const result = array.filter((item) => item !== 8);

If we want to change our original array, it becomes a bit more tricky. We should use a for loop and begin iterating at the end of the array in order to make sure our indices are correct as we go through the items:

for (let i = array.length - 1; i > 0; i--) {
  if (array[i] === 8) {
    array.splice(i, 1);
  }
}

Counting the occurrences of 8

Here is our next problem. We want to know how many times 8 occurs in our array. Basically, what we are trying to achieve is to reduce the entire array to the number of times we see 8 in there.

So let's do it!

const occurrencesOf8 = array.reduce((count, item) => {
  if (item === 8) {
    count++;
  }
  return count;
}, 0);

Find an element

Another common problem we might encounter is to find a certain element in an array.

Let's say we want to find the number 6 and we also care about its index for some reason. The best way to approach this would be with indexOf:

const index = array.indexOf(6); // 1

And if we want to know the index of the last occurrence?

const index = array.lastIndexOf(6); // 6

But what is we just want to know if a certain item exists in an array. Then includes is our best friend:

const has6 = array.includes(6); // true

How about if we want to find the first item which satisfies a condition. For example, let's find an item in our array that is greater that 5. In this case, we can take advantage of find :

const greaterThan5 = array.find((item) => item > 5); // 6

Check for odd numbers

Let's check if every number in our array is an odd number. Conveniently, we can use every for this:

const areAllNumbersOdd = array.every((item) => item % 2 === 1); // false

And if we want to know whether there is at least one odd number, some is what we need:

const isThereAnOddNumber = array.some((item) => item % 2 === 1); // true

Return the first three numbers larger than 5

What if, for some reason, we need to create an array with only the first 3 numbers from our original array which are greater than 5?

We could use some of the more succinct methods from above to achieve this. But there is a limitation. What we want is to loop over the array until we find those items and then break out of the loop to avoid unnecessary work. This is not possible with filter or forEach.

We need to use a for loop.

let count = 0;
const result = [];

for (let number of array) {
  if (number > 5) {
    result.push(number);
    count++;
    if (count === 3) {
      break;
    }
  }
}

And if we wanted to record the indices, rather than the numbers themselves, we might do something like this:

let count = 0;
const result = [];

for (let i = 0; i < array.length; i++) {
  if (array[i] > 5) {
    result.push(i);
    count++;
    if (count === 3) {
      break;
    }
  }
}

Conclusion

The list above is not exhaustive. It is only meant as an illustration of the most common (albeit somewhat simplistic) scenarios where we need to loop over arrays in JavaScript. The goal is to think critically about the instruments we have at our disposal and do our best to use right tool for the job.

Happy coding! ✨

Join my newsletter

Subscribe to get my latest content by email.

I will never send you spam. You can unsubscribe at any time.

MORE ARTICLES

© 2022 Iva Kop. All rights reserved

Privacy policyRSS