JavaScript Array forEach() Method

The JavaScript forEach() method is designed to iterate through each element in an array and execute a provided function once for each element. This enables developers to perform specific operations or computations on each element of the array in a concise and efficient manner.

However, it is important to note that the forEach() method skips empty or undefined elements in the array. In other words, if an array contains empty slots or elements with undefined values, the provided function will not be executed for those elements during the iteration process. This behavior ensures that the forEach() method focuses solely on valid and meaningful elements within the array, preventing unnecessary iterations and improving the overall performance and accuracy of the operation.

const myArry = ['One', 'Two', 'Three']; myArry.forEach(item => console.log(item));
One Two Three

It is important to note that, don't use forEach if the callback does asynchronous work and you want the forEach to wait until that work is done.

forEach() callback function

Additionally, ECMAScript 5 has added a forEach method to Array.prototype which can be used to enumerate over an array using a calback :

arr.forEach(function (val, index, theArray) { //code });

callbackFn is invoked with three arguments:

  1. value of the element.
  2. index of the element.
  3. Array object being traversed.
const myArry = ['One', 'Two', 'Three']; myArry.forEach(function (item, index) { console.log(item, index); });
One 0 Two 1 Three 2

javascript for each loop

It is crucial to highlight that the Array.prototype.forEach method in JavaScript does not terminate the iteration when the callback function returns false. Unlike traditional imperative loops that can be interrupted using a "break" statement, forEach continues executing the callback for all elements in the array, regardless of the return value of the callback.

To emulate the behavior of breaking out of a loop, developers can employ other array methods such as Array.prototype.some() or Array.prototype.every() that return a boolean value based on specific conditions. Alternatively, filtering the array elements before iterating can also be a viable approach. By using methods like Array.prototype.filter(), developers can create a new array with only the desired elements, and then use forEach() on this filtered array., for example:

var find = 'doe'; var arr = [ { id: 100, user: 'john' }, { id: 101, user: 'doe' } ]; var results = arr.filter(function(node) { return node.user === find; }); console.log(results);
[ { id: 101, user: 'doe' } ]


Adopting these alternative strategies not only ensures effective array manipulation but also promotes a more functional programming style, which is often favored in modern JavaScript development for its readability and maintainability.