All The Ways You Can Loop Arrays in Javascript

Shahed Nasser - Apr 6 '21 - - Dev Community

This article was originally published on my personal blog

Whenever you want to loop through an array in Javascript, the common approach taken is using the for loop. Although this is a valid choice, there are many other approaches that you can take to loop through an array in Javascript.


forEach

forEachallows you to loop through all items in an array. For example, a for loop like this:

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

will become:

arr.forEach((item) => console.log(item));
Enter fullscreen mode Exit fullscreen mode

This eliminates the need to keep using the index to access the item, especially when the items in the array are objects and accessing their properties can become a hassle while using the index (unless you assign it to a new variable in the loop.)

You can also access the index as well:

arr.forEach((item, index) => console.log(item, index));
Enter fullscreen mode Exit fullscreen mode

map

map loops through an array, and returns a new array. This is helpful when you are looping through an array, but also are modifying it.

For example, to do this in a for loop:

for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i] + 1;
}
Enter fullscreen mode Exit fullscreen mode

Can be done this way in map:

arr = arr.map((item) => item + 1);
Enter fullscreen mode Exit fullscreen mode

You can also assign it to a new array:

const newArr = arr.map((item) => item + 1);
Enter fullscreen mode Exit fullscreen mode

You can access the index as well:

const newArr = arr.map((item, index) => item + index);
Enter fullscreen mode Exit fullscreen mode

reduce

reduceallows you to loop through an array and accumulate the result from previous iterations up to the current iteration. In the end, a single result is added.

For example, let's say you want to get the sum of elements in an array. Using for loop you can do it like this:

let sum = 0;
for (let i = 0; i < arr.length; i++){
    sum += arr[i]
}
Enter fullscreen mode Exit fullscreen mode

Usingreduce, you can do it this way:

const arr = [1, 2, 3, 4];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue);
Enter fullscreen mode Exit fullscreen mode

Theaccumulatorparameter is the result after the last iteration before the current one, and its value, in the end, will be the value returned. By default, its initial value is the value of the first element and the iteration starts from the second element. So, in the example above, in the first iterationaccumulatorwill be 1 andcurrentValuewill be 2. 1 + 2 is 3 so in the second iterationaccumulatorwill be 3 andcurrentValuewill be 3 (since it's the item in the array that is after 2), and so on. In the end, the returned value will be 10.

You can also passinitialValueto set the initial value to be different than the first element. IfinitialValueis provided, the iteration will start from the first element. PassinginitialValueis also helpful if you're not sure if there are items in your array, asreducethrows an error if the array is empty and noinitialValueis supplied.

An example of usinginitialValue:

const arr = [1, 2, 3, 4];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
Enter fullscreen mode Exit fullscreen mode

withinitialValueset to 0, in the first iterationaccumulatorwill be 0 andcurrentValuewill be 1 (starting from the first element in the array).


every

every allows you to loop through an array and check if all the items in the array return true in the callback function provided. This is helpful when you are looping through an array to make sure it's valid for a certain validation process. The loop will stop and return false whenever it encounters an item that does not return true in the callback function.

For example, to test that all the items in the array are greater than 0, you can do it like this withforloop:

let allGreater = true;
for (let i = 0; i < arr.length; i++){
    if (arr[i] <= 0) {
        allGreater = false;
        break;
    }
}
console.log(allGreater);
Enter fullscreen mode Exit fullscreen mode

To do this usingevery:

const allGreater = arr.every((item) => item > 0);
console.log(allGreater);
Enter fullscreen mode Exit fullscreen mode

It will test that eachitemis&gt; 0and if one of the items isn't, it will stop the loop and return false.

If you don't need to actually store the value in a variable like in the example above, you can just:

console.log(arr.every((item) => item > 0));
Enter fullscreen mode Exit fullscreen mode

You can also pass theindexas a second parameter withitem.


some

Unlikeevery,someallows you to loop through an array and check if at least one item returns true for the callback function. Once an item is found that passes the test provided, the loop will stop and return true. If no item is found that passes the test provided, the loop will return false.

For example, to check that at least one item is greater than 0 in the array using for loop:

let hasGreater = false;
for (let i = 0; i < arr.length; i++){
    if (arr[i] > 0) {
        hasGreater = true;
        break;
    }
}
console.log(hasGreater);
Enter fullscreen mode Exit fullscreen mode

To do this usingsome:

const hasGreater = arr.some((item) => item > 0);
console.log(hasGreater);
Enter fullscreen mode Exit fullscreen mode

You can also eliminate assigning it to a variable if you don't need it:

console.log(arr.some((item) => item > 0));
Enter fullscreen mode Exit fullscreen mode

You can access the index by passing it as a second parameter to the callback function.


filter

filterloops through an array and returns a new array with only the elements that returntruein the callback function.

For example, to get only the elements that are greater than zero in the array, you can do it this way with for loop:

const greaterArr = [];
for (let i = 0; i < arr.length; i++){
    if (arr[i] > 0){
        greaterArr.push(arr[i]);
    }
}
console.log(greaterArr);
Enter fullscreen mode Exit fullscreen mode

To do this usingfitler:

const greaterArr = arr.filter((item) => item > 0);
console.log(greaterArr);
Enter fullscreen mode Exit fullscreen mode

You can also access the index by passing a second argument to the callback array.


find

Withfindyou can loop through an array to find the first element that returns true for a certain function. Once the element is found, the loop will stop and the element will be returned. If no element is found that satisfies the validation,undefinedwill be returned. This is similar tosome, except thatfindreturns the element whereassomejust returns a boolean.

For example, to find an element in the array that is greater than 0 using for loop:

let greaterThan = null;
for (let i = 0; i < arr.length; i++){
    if (arr[i] > 0){
        greaterThan = arr[i];
        break;
    }
}
console.log(greaterThan);
Enter fullscreen mode Exit fullscreen mode

To do this usingfind:

const greaterThan = arr.find((item) => item > 0);
console.log(greaterThan);
Enter fullscreen mode Exit fullscreen mode

You can also access the index by passing a second argument to the callback array.


findIndex

This is similar tofind, except that it returns the index of the element. If no element is found, it returns -1.

For example, to find the index of an element in the array that is greater than 0 using for loop:

let greaterThan = -1;
for (let i = 0; i < arr.length; i++){
    if (arr[i] > 0){
        greaterThan = i;
        break;
    }
}
console.log(greaterThan);
Enter fullscreen mode Exit fullscreen mode

UsingfindIndex:

const greaterThan = arr.findIndex((item) => item > 0);
console.log(greaterThan);
Enter fullscreen mode Exit fullscreen mode

You can also access the index by passing a second argument to the callback array.


Browser Compatibility

It should be noted that all of these functions are compatible with modern browsers, however, its compatibility in IE starts from IE9. So, if you need to make your code compatible with older browsers, you'll probably need to use a Polyfill.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .