We are often required to loop through the array elements and perform some action using them. We can do this using for
loop, but the array forEach()
method is the new way to loop through arrays.
How forEach() method works
The forEach()
method iterates over each array element and executes a function for them. Syntax:
array.forEach(callback, thisArg);
Here the callback is a function that executes for every array element, and thisArg is a value to use as this
inside callback. Let’s see one example.
const foods = ['bread', 'rice', 'meat', 'pizza']; foods.forEach((food) => { console.log(food); });
Output
bread rice meat pizza
The callback function accepts 3 arguments.
- Current element for which the function is being called (required).
- Index of the element in the original array (optional).
- Original array (optional).
Let’s see one example using all these three arguments. In this example, we will remove duplicates from an array.
const arr = [20, 30, 15, 30, 40, 15]; const unique = []; arr.forEach((item, index, array) => { if(index === array.indexOf(item)) { unique.push(item); } }); console.log(unique); // [20, 30, 15, 40]
Here in the callback function, we are comparing the index of the current item with the index of that item in the original array.
The indexOf()
method returns the index of the first occurrence of matched element in the array. That means if the same element is present more than once in the array, then indexOf()
will return the index of the first element from the left.
So if the index of the current element and the index returned by indexOf()
don’t match, then that element exists more than once. Only the unique elements will be pushed into the unique
array.
Array with empty values
The forEach()
method doesn’t invoke the callback function for empty values.
const arr = [20, 30]; arr[5] = 50; console.log(arr); // [20, 30, empty × 3, 50] arr.forEach((item) => { console.log(item); });
Output
20 30 50
Here the callback function was not invoked for all the 3 empty values.
Terminating or skipping the forEach loop
Unlike for
loop, we cannot use the break
or continue
keywords inside the forEach()
method. To terminate forEach()
, we need to throw an exception inside it. Similarly, we need to use the return
statement to skip the current iteration instead of the continue
keyword.
const arr = [20, -45, 30, 15, 30, 40, 15]; arr.forEach((item, index) => { if (item < 0) return; if (index === 3) { throw new Error("Terminating forEach"); } console.log(item); });
Output
20 30 Uncaught Error: Terminating forEach
If you are required to use
break
orcontinue
in the loop, then in that case usefor
loops (for
,for…of
).
Example to use thisArg
In this example, we will filter even and odd numbers from an array and set it to the respective object properties.
function filterNumbers() { this.even = []; this.odd = []; } const numbers = [20, 83, 15, 58, 49, 62]; const obj = new filterNumbers(); numbers.forEach(function (item) { if (item % 2 === 0) this.even.push(item); else this.odd.push(item); }, obj); console.log(obj.even); // [20, 58, 62] console.log(obj.odd); // [83, 15, 49]
Here the instance of filterNumbers
is passed to forEach()
to use as this
inside the callback.
Related
- Different Ways to iterate through Objects and Arrays in JavaScript
- map() and filter() methods of Array in JavaScript
- 6 ways to find elements in Array in JavaScript
Web Developer by Profession, Blogger by Passion.
JavaScript | React | Next | Angular | Vue | HTML | CSS