In this post we will explore all the ways we can iterate through an array in JavaScript. Let’s loop! 🔄
Standard ways
- forEach
- for…of
- for…in
- for
- while
Other ways – here the goal is to not iterate but get results from array data
- map
- filter
- reduce
- some
- every
Different ways to iterate a JS array
const arr = [1, 2, 3, 4, 5];
// forEach - iterates through each value.
arr.forEach((n, index) => console.log("forEach", n, "index", index));
// for...of loop - iterates through each value.
for (n of arr) {
console.log("for...of", n);
}
// for...in loop - iterates through each index.
for (n in arr) {
console.log("for...in", arr[n]);
}
// for loop - iterates through each index.
for (let i = 0; i < arr.length; i++) {
console.log("for loop", arr[i]);
}
// while loop - iterates through each index.
let j = 0;
while (j < arr.length) {
console.log("while loop", arr[j]);
j++;
}Code language: JavaScript (javascript)Other ways to process array values
const arr = [1, 2, 3, 4, 5];
// map - used to transform existing values and create a new array
const newArr = arr.map((n, index) => {
console.log("map", n, "index", index);
return n * 2;
});
console.log("newArr", newArr); // [2,4,6,8,10]
// filter - filter required values
const filtered = arr.filter((n, index) => {
console.log("filter", n, "index", index);
return n % 2 === 0;
});
console.log("filtered", filtered); // [2,4]
// reduce - acumulate all values
const sum = arr.reduce((acc, n, index) => {
console.log("reduce", n, "index", index);
return acc + n;
}, 0);
console.log("sum", sum); // 15
// some - check if atleast one element pass the test
// Stops running if one element pass the test
const some = arr.some((n, index) => {
console.log("some", n, "index", index);
if (n % 2 === 0) {
return true;
}
});
console.log("some", some); // true
// every - check if all elements pass the test
// Stops running if one element fails the test
const every = arr.every((n, index) => {
console.log("every", n, "index", index);
if (n % 2 === 0) {
return true;
}
});
console.log("every", every); // false
Code language: JavaScript (javascript)