Arrays are single variables that store elements of different datatypes so that they can be accessed from one variable.
There are a number of values in the list, and each value is referred to as an element, which is specified by an index.
Because these variables contain a list of elements, you might want to create a list of these elements so that you can perform individual functions with them and much more.
The following is an interactive demo showing how to loop through an array in JavaScript:
const odds = [1, 3, 5, 7, 9]
/*
CHALLENGE:
use a forEach console.log each
element in the odds array
*/
odds.forEach((num) => {
console.log(num)
})
What are Loops in JavaScript?
It is a computer program that allows us to repeat a specific operation a predetermined number of times without having to write it individually each time.
As an example, if we want to output the elements in an array, rather than using the index number to do so one by one, we can loop through and perform this operation once.
In this article, we will cover the most commonly used approaches for looping through an array in JavaScript.
We will use the following array for this article:
const scores = [22, 54, 76, 92, 43, 33];
Way to Loop Through an Array with a While Loop in JavaScript
While loops can be used to evaluate a condition enclosed in parenthesis (). If the condition is true, the code inside the while loop is executed. If it is false, the loop ends.
Using the length property of an array, we can specify that the loop should continue until the last element is reached.
Let’s now use the while loop method to loop through the array:
let i = 0;
while (i < scores.length) {
console.log(scores[i]);
i++;
}
Each element in our array will be returned one by one as follows:
22
54
76
92
43
33
Using the loop above, we initialized the index number with 0. After that, the index number will continue to increase, and we will output each element until the condition we set returns false, indicating that we have reached the end of the array. Since the array’s last index is 5, the condition will no longer be executed when i = 6.
Way to Loop Through an Array with a do…while Loop in JavaScript
Unlike a while loop, a do…while loop executes the body first before evaluating the condition for subsequent executions. This means the loop’s body is always executed.
To see how it works, let’s use a do…while loop:
let i = 0;
do {
console.log(scores[i]);
i++;
} while (i < scores.length);
Each element in our array will be returned by this method:
22
54
76
92
43
33
The body of the loop will run first before evaluating any condition set. For example, if we set i to 6 and it is not less than scores.length, the body will run first.
let i = 6;
do {
console.log(scores[i]);
i++;
} while (i < scores.length);
Since we do not have an element in the array of index 6, we will get an undefined, but as you can see, it ran once before stopping.
Way to Loop Through an Array with a for Loop in JavaScript
If certain conditions are met, the for loop executes a block of code repeatedly.
Since the initialization, condition, and iteration are all handled within the bracket, we do not need to initialize the index first:
for (let i = 0; i < scores.length; i++) {
console.log(scores[i]);
}
As with other methods, this will return all the elements:
22
54
76
92
43
33
Way to Loop Through an Array with a for…in Loop in JavaScript
For…in loops are easier than for…else loops because they give us the key, which we can then use to get the values from the array:
for (i in scores) {
console.log(scores[i]);
}
Our array will be output as follows:
22
54
76
92
43
33
Way to Loop Through an Array with a for…of Loop in JavaScript
A for…of loop iterates over iterable objects such as arrays, sets, maps, strings, and so on. It has the same syntax as the for…in loop, but instead of getting the key, it gets the element.
Later versions of JavaScript ES6 introduced this method for looping through arrays.
for (score of scores) {
console.log(score);
}
To get each element of our array, we no longer need to use the index:
22
54
76
92
43
33
Way to Loop Through an Array with a forEach Loop in JavaScript
ForEach() loops through any array, executing a callback function once for each array element in ascending index order.
The following is an advanced method that can do much more than simply loop through each element:
scores.forEach((score) => {
console.log(score);
});
This can be written in one line as follows:
scores.forEach((score) => console.log(score));
The output will be the same as all previous methods:
22
54
76
92
43
33
Final thoughts
The purpose of this article was to examine six different/standard methods for looping through an array.
In order to determine which method is better for you, easier to read, and cleaner to use, you need to understand all of these methods.
Explore 200+ expert articles on web development. Check out my blog for more captivating content.
Leave a comment