

Iterating Over Arrays in JavaScript: 4 Methods Compared
source link: https://code.tutsplus.com/tutorials/iterating-over-arrays-in-javascript--cms-93864
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Iterating Over Arrays in JavaScript
If you already understand the basics of JavaScript arrays, it's time to take your skills to the next level with more advanced topics. In this series of tutorials, you'll explore intermediate-level topics for programming with arrays in JavaScript.
Iterating over or looping through arrays is something we have to do in almost every 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 an output or transforming it.
There are many methods that you can use to iterate over arrays in JavaScript. In this tutorial, we will learn about them all while discussing the advantages or disadvantages of each in detail.
Method | Advantage | Disadvantage | ||
---|---|---|---|---|
for loop | can exit early with break , works with async code, universal browser support |
verbose and somewhat error-prone | ||
forEach() method |
concise and easy to read | no async 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 elements |
Method | Flow Control With Break and Continue? | Works With Async Code? | Browser Support | Notes |
---|---|---|---|---|
for loop | yes | yes | all browsers | more verbose syntax, off-by-one errors |
forEach() method |
no | modern browsers | concise and chains after other functions (ie. map ) |
|
for...of loop |
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 from 0. This means that the first element will be accessible by using array_name[0]
in your code. Similarly, for an array with n
elements, the last element will be accessible by using array_name[n - 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 |
|
console.log(last); |
|
// Outputs: Zebra |
Iterating Using a for
Loop
One of the most common ways of looping through arrays is the for
loop. The for
loop initializes our iterating variable with a value of 0 to start looping from the first element. Since we want to iterate over the whole 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 by using array_name[length - 1]
.
The following code snippet shows us how to loop through an array sequentially using a for
loop:
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 |
Dog |
|
Lion |
|
Cat |
|
Zebra |
|
*/ |
Notice how we are using the less than operator (<
) instead of the less than or equal to operator (<=
) as our loop ending condition.
Two advantages of using a for
loop when looping through arrays are that it is widely supported and it allows you to control the flow of the loop through break
and continue
statements. You can exit the loop as soon as you find what you're looking for. A for
loop also works well when you are dealing with asynchronous code.
The disadvantage is that it is a bit verbose, and you are likely to make off-by-one errors once in a while.
Iterating Using the forEach()
Method
You can also use the built-in forEach()
method to iterate over arrays in JavaScript. This method accepts a callback function as its parameter, which is executed once for each array element. The callback function can be defined somewhere else, and it can be an inline function or an arrow function.
The callback function can accept three different arguments:
- the current element itself
- the index of the current element
- the array on which we called the
forEach()
method
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 |
*/ |
As you can see, using the forEach()
method makes our code much more concise. Here is another example that uses the second argument of the callback function.
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 |
Animal 4: Cat |
|
Animal 5: Zebra |
|
*/ |
Using forEach()
works great for simple iteration over arrays. However, you can't use break
and continue
to exit the loop midway and change the program flow. Another downside of using forEach()
is that you won't be able to use asynchronous code with this method.
Iterating Using the for...of
Loop
The ES6 standard added a lot of new features to JavaScript. One of them was the concept of iterators and iterables. You can use the for...of
loop to iterate over values in any object which implements the @@iterator
method. Built-in types such as Array, String, Set, or Map can use a for...of
loop to iterate over their values.
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 |
Cat |
|
Zebra |
|
*/ |
Using the for...of
construct for iteration has many advantages. For instance, you can use it to iterate over other built-in iterable types as well. Other than that, it allows you to break out of the loop and control the program flow using the break
or continue
statements.
The only potential downside is slightly less browser support, but it all depends on your target audience.
Iterating Using the for...in
Loop
You can also loop through an array using a for...in
statement. 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 I mentioned earlier, this statement will iterate over all the integer and non-integer properties, even if they are inherited. When we are iterating over arrays, we are usually just interested in integer keys.
The traversal order for the for...in
loop is well defined, and it begins with the traversal of non-negative integer keys. The non-negative integer keys are traversed in ascending order by value. Other string keys are then traversed in the order of their creation.
One type of array which you can traverse with a for...in
loop better than other methods is a sparse array. For example, a for...of
loop will iterate over all the empty slots in the sparse array, while a for...in
loop won't.
Here is an example of iterating over a sparse array with a for...in
loop:
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]}`); |
} |
|
} |
|
/* Outputs: |
|
Position 0: pie |
|
Position 548: language |
|
Position 3497: hungry |
|
*/ |
You might have noticed that we have used a static method called Object.hasOwn()
to check if the specified property for our queried object is indeed its own property.
Final Thoughts
You can always use a regular for
loop to iterate over arrays. It allows you to control the program flow with the help of the break
and continue
keywords, while also supporting asynchronous code. On the other hand, it does require you to be careful about off-by-one errors.
The forEach()
method provides a shorter way of looping through an array, but it doesn't work well with asynchronous code. You also can't break 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 also works with asynchronous code. There is also no need to worry about off-by-one errors.
Finally, the for...in
loop is not a recommended way of looping through arrays. However, it can prove useful if the arrays you are traversing are very sparse.
The thumbnail for this post was generated with OpenAI's DALL-E 2.
Recommend
-
35
This post examines a particular, seemingly simple problem: given ownership of a Rc<Vec<u32>> , can we write a function that returns an impl Iterator<Item = u32> ? It turn...
-
48
Reading Time: 9 minutes How often do you work with JavaScript arrays? There has been a lot of talk about ES5, ES6 and ES7. Yet, it almost seems like there...
-
6
Iterating Over a Bitset in Java Feb 23, 2018 | Richard Startin | javavector
-
5
Tutorial Four Methods to Search Through Arrays in JavaScript JavaScript
-
5
Iterating Over a Generic Sequence in Swift Here’s a goofy bit of generic programming I do all the time in Swift—ironically, it’s one thing C++ makes easier than Swift! The use case is simple: I want a function to...
-
6
Notes on Modern UI Development: Iterating over the other 80% Introduction I have been working on a modern typing training application for the last couple of days. One of the main motivations was to build an app with a mod...
-
9
ECMAScript 2023 spec for JavaScript adds methods for arrays ECMAScript 2023, due in June, is set to add new methods for searching and changing arrays, al...
-
7
This tutorial will discuss multiple ways to skip certain elements while iterating over a set in C++. Table Of Contents Advertisements
-
8
Modify elements while Iterating over a Set in C++ August 25, 2023 / C++, std::set...
-
4
Dynamically create a ref for items when iterating over them in lit.dev templates 28.11.2023
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK