user
How to iterate through JavaScript arrays?
alphonsio

Here are the three most common options to iterate through JS arrays:

Sequential for loop

var myArray = ['First', 'Second', 'Third'];
for (var i = 0; i < myArray.length; i++) {
    // Do awesome stuff here
    console.log(myArray[i]);
}

Using forEach

var myArray = ['First', 'Second', 'Third'];
myArray.forEach(function (value, index) {
    // Do awesome stuff here
    console.log(index, value);
})

ES6 for..of statement

var myArray = ['First', 'Second', 'Third'];
for (const value of myArray){
    // Do awesome stuff here
    console.log(value);
}

How to iterate through JavaScript arrays

Let's take a closer look at all the options available for browsing an array in JavaScript.
Iterating through JavaScript arrays can be done using several methods depending on your use case. Here are the most common ones:

1. Using a for loop

The classic way to loop through arrays. Gives you full control over the iteration.

let arr = [1, 2, 3, 4];

for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Here is a live example:

---

2. Using for...of

A simpler syntax for iterating over array elements directly.

let arr = [1, 2, 3, 4];

for (let value of arr) {
  console.log(value);
}

Here is a live example:

---

3. Using forEach

An array method that executes a provided function once for each array element.

let arr = [1, 2, 3, 4];

arr.forEach((value, index) => {
  console.log(`Index: ${index}, Value: ${value}`);
});

Here is a live example:

---

4. Using map

Creates a new array by applying a function to each element.

let arr = [1, 2, 3, 4];

let newArr = arr.map(value => value * 2);
console.log(newArr); // [2, 4, 6, 8]

Here is a live example:

---

5. Using for...in

Not recommended for arrays, but it works. Mainly used for objects as it iterates over enumerable properties.

let arr = [1, 2, 3, 4];

for (let index in arr) {
  console.log(arr[index]);
}

Here is a live example:

---

6. Using while or do...while

Great if you need a condition-based loop.

let arr = [1, 2, 3, 4];
let i = 0;

while (i < arr.length) {
  console.log(arr[i]);
  i++;
}

Or:

let j = 0;
do {
  console.log(arr[j]);
  j++;
} while (j < arr.length);

Here is a live example:

---

7. Using reduce

Mainly for accumulating values but can iterate too.

let arr = [1, 2, 3, 4];

arr.reduce((acc, value) => {
  console.log(value);
  return acc;
}, 0);

Here is a live example:


8. Using filter

If you want to loop while filtering elements.

let arr = [1, 2, 3, 4];

let filteredArr = arr.filter(value => value > 2);
console.log(filteredArr); // [3, 4]

Here is a live example:


Which one to use?

  • for or for...of: Use for most cases where you need flexibility.
  • forEach: When you don't need to break out of the loop and want readability.
  • map or reduce: If transforming or accumulating data.
  • filter: If selecting specific elements.
  • Avoid for...in: It's more for objects, not arrays.