Five Ways to Loop Through a JavaScript Array

Learn the different methods to loop through arrays in JavaScript

Photo by Zan on Unsplash

https://gitconnected.com/portfolio-api

In JavaScript there are many ways to loop through Array.

  1. Loops which can break or skip (continue) an iteration:
  • for
  • while
  • do…while
  • for…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 break statement
  • We can skip the current iteration using continue statement.

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

https://gitconnected.com/portfolio-api

Leave a comment

Design a site like this with WordPress.com
Get started