Learn the different methods to loop through arrays in JavaScript
https://gitconnected.com/portfolio-api
In JavaScript there are many ways to loop through Array.
- Loops which can
breakor skip (continue) an iteration:
forwhiledoâŚwhileforâŚin
2. Loops which we cannot break or skip an iteration:
forEach
Tip: To create an array with a number elements
var array = Array.from(new Array(10000).keys());
1. for
let arrayLength = array.length;
for(let i = 0 ; i < arrayLength; i++) {
let val = array[i];
}
- We can break the loop using the
breakstatement - We can skip the current iteration using
continuestatement.
2. while
let i = 0;
let arrayLength = array.length;
while(i < arrayLength ) {
let val = array[i];
i++;
}
We can also use break and continue in a while loop. But when we are using a while loop we need to take care of the increment for the next iteration. If we forgot the increment part, then it may result in an infinite loop.
3. doâŚwhile
I donât prefer using doâŚwhile loop for iterating an array. A doâŚwhile will always perform an action once before checking for the condition, meaning it will execute even if our array is empty. This means it should only be used for specific cases.
let i = 0;
let arrayLength = array.length;
do {
let val = array[i];
i++;
} while (i <arrayLength);
We can also use break and continue in a doâŚwhile loop.
4. forâŚin
for (let val in array) {
// operation
}
We can use break and continue in a forâŚin loop. These loops can also be used to iterate through objects.
5. forEach
We use the forEach if we need to execute an operation on every element of the array. We cannot break or skip iteration in this loop. Using a forEach is also a more functional and declarative syntax which makes it the preferred choice by many developers.
array.forEach(val => {
// operation
});
There is a benchmark test written to find the time difference between these different functions here: https://jsperf.com/for-vs-foreach/654. The basic for loop is actually the fastest in the test cases.
In addition to the above methods, we can also use map, filter, and reduce which are more advanced JavaScript functions. These are used for specific cases that you can learn about in the article below:
https://gitconnected.com/portfolio-api
https://gitconnected.com/portfolio-api
Follow Javascript Jeepđđ¨.
































