Iteration over arrays in JavaScript: 4 methods compared


If you already know the basics of JavaScript arrays, it’s time to take your skills to the next level with more advanced topics. In this tutorial series, you’ll explore intermediate-level topics for programming with arrays in JavaScript.

Iterating or looping through arrays is something we need to do in almost any project that involves working with arrays. There are many reasons why you might need to loop over an array, such as showing the array data as output or transforming it.

There are many methods you can use to iterate over arrays in JavaScript. In this tutorial, we’ll get to know them all by discussing the advantages or disadvantages of each in detail.








method flow control with break and continue advantage downside
per cycle can date soon with breakworks with asynchronous code, universal browser support verbose and somewhat error-prone
forEach() method concise and easy to read no asynchronous support, no early exit with break
for...of loop works with other iterable types, allows early exit, syntax reduces errors less support in older browsers
for...in loop efficient on sparse arrays, allows early exit may return unexpected inherited items








method flow control with pause and continue? does it work with asynchronous code? browser support Notes
per cycle YES YES all browsers more verbose syntax, off-by-one errors
forEach() method

NO

NO modern browsers concise and chains after other functions (eg. map)
for...of loop

YES

YES modern browsers simple syntax reduces errors
for...in loop YES YES all browsers efficient for sparse arrays, can return unexpected (inherited) elements

Basics of accessing array elements

Let’s start with the basics of accessing array elements using their index. Array indexing in JavaScript starts at 0. This means that the first element is accessible using array_name[0] in your code Similarly, for an array with n items, the last item will be accessible using array_name[n - 1].

1
let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];
2

3
let first = animals[0];
4

5
let last = animals[4];
6

7
console.log(first);
8
// Outputs: Fox
9

10
console.log(last);
11
// Outputs: Zebra

Iterate using a for Loop

One of the most common and well-known ways to loop through arrays is the for loop. THE for loop initializes our iteration variable with a value of 0 to start the loop from the first element. Since we want to iterate over the entire array we need to calculate the length of the array which is easy to do with the length property. The last element in our array will then be accessible using array_name[length - 1].

The following code snippet shows us how to iterate through an array using a for loop:

1
let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];
2

3
let animal_count = animals.length;
4

5
for(let i = 0; i < animal_count; i++) {
6
  console.log(animals[i]);
7
}
8
/* Outputs:
9
Fox
10
Dog
11
Lion
12
Cat
13
Zebra
14
*/

You should notice how we are using the less than operator (<) instead of the less than or equal to operator (<=) as our end-of-cycle condition.

Two benefits of using a for loop when looping arrays is that it is widely supported and allows you to control the flow of the loop through break AND continue statements. You can get out of the loop as soon as you find what you are looking for. A for loop also works well when you’re dealing with asynchronous code.

The downside is that it is a bit long-winded and mistakes are likely to be made from time to time.

Iterate using the forEach() Method

You can also use the built-in forEach() method for iterating over arrays in JavaScript. This method takes a callback function as a parameter which is executed once for each element of the array. The callback function can be defined somewhere else, be it an inline function or an arrow function.

The callback function can take three different arguments. The first is the current element itself. The second is the index of the current element while the last argument is the array we called the on forEach() method.

1
let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];
2

3
animals.forEach(animal => console.log(animal));
4
/* Outputs:
5
Fox
6
Dog
7
Lion
8
Cat
9
Zebra
10
*/

As you can see, using the forEach() it makes our code much more concise. Here’s another example using the second argument of the callback function.

1
let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];
2

3
animals.forEach((animal, idx) => {
4
  console.log(`Animal ${idx + 1}: ${animal}`);
5
});
6
/* Outputs:
7
Animal 1: Fox
8
Animal 2: Dog
9
Animal 3: Lion
10
Animal 4: Cat
11
Animal 5: Zebra
12
*/

Using forEach() works great for simple iteration over arrays. However, you cannot use break AND continue to exit the loop midway through the program flow change. Another downside of using forEach() is that you won’t be able to use asynchronous code with this method.

Iterate using the for...of Loop

The ES6 standard has added many new features to JavaScript. One of them was the concept of iterators and iterables. You can use the for...of loop to iterate over the values ​​in any object that implements the @@iterator method. Built-in types like Array, String, Set, or Map can use a for...of loop to iterate over their values.

1
let animals = ["Fox", "Dog", "Lion", "Cat", "Zebra"];
2

3
for(let animal of animals) {
4
  console.log(animal);
5
}
6
/* Outputs:
7
Fox
8
Dog
9
Lion
10
Cat
11
Zebra
12
*/

Using the for...of construct for iteration has many advantages. For example, you can use it to iterate over other built-in iterable types as well. Beyond that, it lets you get out of the loop and control the flow of the program using the file break OR continue statements.

The only potential downside is slightly less browser support, but that all depends on your target audience.

Iterate using the for...in Loop

You can also iterate through an array using a for...in declaration. This will loop over all enumerable string properties of an object. This also includes inherited enumerable properties.

I would like to mention here that iterating over a loop using a for...in statement is not recommended. This is because, as mentioned above, this statement will iterate over all integer and non-integer properties even if they are inherited. When we’re iterating over arrays, we’re usually only interested in integer keys.

The traversal order for the for...in loop is well defined and starts traversing non-negative integer keys first. Non-negative integer keys are examined in ascending order of value. Other string keys are then traversed in the order of their creation.

An array type that you can traverse with a for...in loop better than other methods are sparse arrays. For example, a for...of loop will iterate over all empty slots in the sparse array while a for...in the cycle will not.

Here is an example of iterating over a sparse array with a for...in loop:

1
let words = new Array(10000);
2

3
words[0] = "pie";
4
words[548] = "language";
5
words[3497] = "hungry";
6

7
for(let idx in words) {
8
  if(Object.hasOwn(words, idx)) {
9
    console.log(`Position ${idx}: ${words[idx]}`);
10
  }
11
}
12
/* Outputs:
13
Position 0: pie
14
Position 548: language
15
Position 3497: hungry
16
*/

You may have noticed that we used a static method called Object.hasOwn() to check if the property specified for our queried object is indeed its property.

Final thoughts

You can always use a regular for loop to iterate over the arrays. It allows you to control program flow with the help of break AND continue keywords while being asynchronous compatible with the code. On the other hand, it requires you to be careful of mistakes one by one.

THE forEach() The method provides a shorter way to iterate through an array but doesn’t work well with asynchronous code. You also can’t get out of loops or control program flow using break AND continue.

THE for...of loop gives us the best of both worlds. We have full control over the program flow and it works even with asynchronous code. You also don’t need to worry about off-by-one errors.

Finally the for...in loop is not a recommended way to loop through arrays. However, it can prove useful if the arrays you’re traversing are very sparse.

The thumbnail for this post was generated with OpenAI’s DALL-E 2.



Source link

By LocalBizWebsiteDesign

Leave a Reply

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