Free UI Resources - UI Dev Made Easy
Javascript

Javascript Array Methods – forEach()

.forEach()

The .forEach() method is a built-in function available on arrays in JavaScript. It is used for iterating over each element in an array and performing a specified action or function on each element. This method is particularly useful when you want to perform some operation on every element of an array without explicitly using a for loop.

#Here's the basic syntax of the .forEach() method:
array.forEach(function(currentValue, index, array) {
  // Code to be executed for each element
});
  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element.
  • array (optional): The array that .forEach() is being applied to.
Here's an example to illustrate how .forEach() works:

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

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

In this example, the .forEach() method iterates through each element in the numbers array and logs the element along with its index.

Keep in mind:

  1. No Return Value: The .forEach() method does not return a new array. It’s mainly used for its side effects (like logging, updating, or modifying elements in-place).
  2. Break or Continue: Unlike a for loop, you cannot break out of a .forEach() loop or use continue to skip to the next iteration. If you need to break or skip, you might need to use a regular for loop.
  3. Performance: In terms of performance, .forEach() is not always the fastest option for looping through arrays, especially when compared to other iteration methods like .map() or traditional for loops. However, its readability and ease of use often make it a good choice for many scenarios.
  4. Arrow Functions: You can also use arrow functions for more concise syntax:
numbers.forEach((number, index) => {
  console.log(`Element at index ${index} is: ${number}`);
});

In summary, the .forEach() method is a convenient way to iterate through array elements and perform actions on each element. It’s a great tool for scenarios where you want to apply a function to every element without the need for complex looping structures.

back to top