Onjsdev

Share


Javascript forEach() Method

How To Use Javascript forEach() Method


By onjsdev

Jan 24th, 2024

JavaScript forEach() is an array method that iterates through an array and executes a callback function on each element in the array.

Syntax

The javascript forEach() method takes a callback function as its parameter:

array.forEach(callback);

A callback function also takes three parameters, including:

  • currentElement: The current element being processed
  • index: The index of the current element in the array
  • arr: The original array itself (array) .

A callback function can be defined as a named, anonymous, or arrow function:

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

// Using a named function:
function callback(currentElement,index,arr) {
  console.log(currentElement);
}
array.forEach(callback);

// Using an anonymous function:
array.forEach(function(currentElement, index, arr) {
   console.log(currentElement);
});

// Using an arrow function:
array.forEach((currentElement, index, arr) => {
  console.log(currentElement);
});

Examples

In the following example, we use the forEach() method to iterate through the array of numbers and print each number and their indexes to the console using the console.log() method.

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

numbers.forEach(function(number, index) {
  console.log(`Index: ${index}, Number: ${number}`);
});

/*

Index: 0, Number: 1
Index: 1, Number: 2
Index: 2, Number: 3
Index: 3, Number: 4
Index: 4, Number: 5

*/

In another example, to sum all the values in the array, we use the forEach method to iterate through each item in the array and add each value to the sum variable.

At the end, the sum variable will contain the total sum of all the values in the array.

const values = [1, 2, 3, 4, 5];
let sum = 0;

values.forEach(value => {
  sum += value;
});

console.log(sum); // Output: 15

Conclusion

In conclusion, the Javascript forEach method is a powerful method while working on arrays. It gets a callback function as an parameter and call this callback function for each element to perform actions over the elements.

If you want to learn more javascript array methods, you can take a look at the following guides:

Thank you for reading.