DEV Community

losetom
losetom

Posted on

forEach() in JavaScript

The forEach() method in JavaScript does not have a built-in return value like methods such as map() and filter() do but its generic properties make it very flexible as whatever callback function is passed in can have whatever functionality we want it to have.

The forEach() method will execute a given function for each array item in an ascending index order.

The callback function for forEach() will be invoked with three given arguments:

  • The value of the element
  • The index of the element
  • The array object being traversed

You can print values of an array to the console for visualization of the functionality.

e.g.
const numbers = [1, 2, 3, 4, 5]
numbers.forEach(itemLog);

function itemLog(item, index, array) {
console.log(item);
}

1
2
3
4
5

This example shows the numbers in the array are simply being printed to the console.


forEach() also allows the user to display the position, or index, of each value in the array.

e.g.

const numbers = [1, 2, 3, 4, 5]
numbers.forEach(itemLog);

function itemLog(item, index, array) {
console.log('a[' + index + '] = ' + item);
}

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5

This example displays the index position of each value in the array.


const numbers = [1, 2, 3, 4, 5]
numbers.forEach(itemLog);

function itemLog(item, index, array) {
console.log(array)

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

This example displays the array being printed as called.


If given an array of numbers, forEach() can also be used to provide the sum of those values in the array.

For this example, I will use an arrow function to show how the code written above can be condensed.

const numbers = [1, 2, 3, 4, 5]

let sum = 0
// To return the sum of an array, it must first start at 0 so, let sum = 0

numbers.forEach(item => {
sum += item
)}

console.log(sum);

15

The value of 15 will be printed to the console as it is the sum of the values provided in the array.


forEach() is not the most useful of the JavaScript array methods but it offers a good alternative to writing lengthy for loops and provides a good visualization of the nature and behavior of arrays when they are being targeted with different methods.

Resources:

https://www.youtube.com/watch?v=SXb5LN_opbA&ab_channel=FlorinPop

https://www.w3schools.com/jsref/jsref_forEach.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Top comments (1)

Collapse
 
pengeszikra profile image
Peter Vivo • Edited

Imho forEach is sign we do some side-effect, like console.log.
I prefer map instead, which is much more cleaner.