Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 20, 2023 01:43 am

Iterating Over Arrays in JavaScript: 4 Methods Compared


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 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.















































methodflow control with break and continue  advantagedisadvantage
for loop   can exit early with break, works with async code, universal browser supportverbose and somewhat error-prone
forEach() method   concise and easy to readno async support, no early exit with break
for...of loop   works with other iterable types, allows early exit, syntax reduces errorsless support in older browsers
for...in loop   efficient on sparse arrays, allows early exitmay return unexpected inherited elements









































methodflow control with break and continue?works with async code?browser supportnotes
for loopyesyesall browsersmore verbose syntax, off-by-one errors
forEach() method

no


nomodern browsersconcise and chains after other functions (ie. map)
for...of loop

yes


yesmodern browserssimple syntax reduces errors
for...in loopyesyesall browsersefficient 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 is 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].















































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

Iterating Using a for Loop


One of the most common and well known ways for 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:



























































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 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 find what you are 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, be an inline function or an arrow function.


The callback function can accept three different arguments. The first one is the current element itself. The second one is the index of the current element while the last argument is the array on which we called the 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() method makes our code much more concise. Here is another example that uses 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 of 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.



















































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 instance, you can use it to iterate over other built-in iteratable 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 first. 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 arrays which 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 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:



































































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 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 break and continue keywords while also being asynchronous code friendly. On the other hand, it does require you to be careful about of-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 provides 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 for loop 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.



Original Link: https://code.tutsplus.com/tutorials/iterating-over-arrays-in-javascript--cms-93864

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code