JavaScript : How to iterates over elements in an array ?

Java Script @ Freshers.in

JavaScript arrays are fundamental data structures used extensively in web development. To manipulate arrays effectively, developers rely on array methods, and one such method is forEach(). In this article, we explore the intricacies of forEach(), its syntax, functionality, and practical applications through illustrative examples.

Understanding forEach()

The forEach() method in JavaScript iterates over elements in an array and executes a callback function for each element. It provides a simple and concise way to perform operations on array elements without the need for explicit looping constructs.

Syntax

The syntax for forEach() is as follows:

array.forEach(callback(currentValue, index, array), thisArg);

Here, array represents the array to be traversed, callback is the function to execute for each element, and thisArg (optional) refers to the value to use as this when executing the callback.

Examples

Let’s delve into examples to understand the utility of forEach() better:

Example 1: Printing Array Elements

const numbers = [1, 2, 3, 4];
numbers.forEach(function(element) {
  console.log(element);
});
// Output:
// 1
// 2
// 3
// 4

Example 2: Modifying Array Elements

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

Example 3: Using thisArg Parameter

const numbers = [1, 2, 3, 4];
let sum = 0;
function addToSum(element) {
  sum += element * this.multiplier;
}
numbers.forEach(addToSum, { multiplier: 2 });
console.log(sum);
// Output: 20 (2*1 + 2*2 + 2*3 + 2*4)
The forEach() method in JavaScript simplifies array iteration and processing, offering an intuitive way to perform operations on array elements.
Author: user