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);
}
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:
for
loopThe 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:
---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:
---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:
---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:
---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:
---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:
---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:
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:
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.for...in
: It's more for objects, not arrays.