How to Use ForEach to Iterate an Array in Javascript

Feb 6, 2024

2 mins read

Published in

Mastering Array Iteration with JavaScript’s forEach Method

Array iteration is a fundamental aspect of programming, allowing developers to efficiently manipulate data stored in arrays. JavaScript provides several methods for iterating over arrays, with forEach() being one of the most commonly used and versatile options. In this blog post, we’ll delve into the forEach() method, exploring its syntax, functionality, and practical applications.

Understanding forEach():

The forEach() method is part of the Array prototype in JavaScript, designed to iterate over each element of an array and execute a provided callback function for each iteration. Its syntax is simple:

1
2
3
array.forEach(callback(currentValue [, index [, array]]) {
  // code block to execute on each element
});

Here’s a breakdown of the parameters:

  • callback: A function to execute on each element in the array.
  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element being processed.
  • array (optional): The array forEach() was called upon. ; Using forEach(): Let’s dive into some practical examples to understand how to use forEach() effectively.

Example 1: Printing Array Elements

1
2
3
4
const array = [1, 2, 3, 4, 5];
array.forEach(element => {
  console.log(element);
});

Example 2: Modifying Array Elements

1
2
3
4
5
const array = [1, 2, 3, 4, 5];
array.forEach((element, index, arr) => {
  arr[index] = element * 2;
});
console.log(array); // Output: [2, 4, 6, 8, 10]

Example 3: Summing Array Elements

1
2
3
4
5
6
const array = [1, 2, 3, 4, 5];
let sum = 0;
array.forEach(element => {
  sum += element;
});
console.log(sum); // Output: 15

Example 4: Using thisArg

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function Counter() {
  this.sum = 0;
  this.count = 0;
}

Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
    ++this.count;
  }, this);
};

const counter = new Counter();
counter.add([1, 2, 3]);
console.log(counter.sum); // Output: 6
console.log(counter.count); // Output: 3

In this blog post, we’ve explored the forEach() method in JavaScript, learning its syntax, parameters, and practical usage scenarios. By mastering forEach(), developers can efficiently iterate over arrays, manipulate data, and streamline their code. Experiment with different examples and use cases to leverage the full potential of forEach() in your JavaScript projects. Happy coding!

Sharing is caring!