JavaScript Array's For Each () Method

An Array represents a collection of elements of different data types, such as strings, objects, numbers, etc., in JavaScript. In any programming language, to access or manipulate elements within an array, you need to use a loop.

JavaScript offers numerous iteration methods, one of which is the forEach() method. Most of these methods serve the same purpose with minor differences.

JavaScript forEach()

The forEach() array method loops through any array, executing a provided function once for each array element in ascending index order. This function is referred to as a callback function.

The forEach loop is a method available on arrays in JavaScript.

It allows you to iterate over each element of an array and apply a function to each element. This is a more concise and elegant way of iterating over arrays compared to using traditional for loops.

Here’s the basic syntax of the forEach loop:

				
					array.forEach(function(currentValue, index, array) {
  // code to be executed on each element
});

				
			
  • currentValue: The current element being processed in the array.
  • index: The index of the current element within the array.
  • array: The array that forEach is being applied to.

Here’s an example of how you might use the forEach loop to iterate through an array and log each element to the console:

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

numbers.forEach(function(number, index) {
  console.log(`Element at index ${index} is ${number}`);
});

				
			

Output:

  • Element at index 0 is 1
  • Element at index 1 is 2
  • Element at index 2 is 3
  • Element at index 3 is 4
  • Element at index 4 is 5

In more modern JavaScript, you can also use arrow function syntax to make the code even more concise:

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

numbers.forEach((number, index) => {
  console.log(`Element at index ${index} is ${number}`);
});

				
			

Keep in mind that the forEach loop doesn’t return a new array; it simply iterates over the existing array. If you want to transform the array or create a new one based on the existing array, you might want to look into methods like map() , filter() , or  reduce().

Leave a Reply

Your email address will not be published. Required fields are marked *