This translation is incomplete. Please help translate this article from English

המתודה forEach() מריצה את הפונקציה שקיבלה עבור כל איבר במערך.


arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);


Function to execute on each element, taking three arguments:
The current element being processed in the array.
index Optional
The index of the current element being processed in the array.
array Optional
The array forEach() was called upon.
thisArg Optional
Value to use as this when executing callback.

ערך החזרה



forEach() קוראת לפונקציה callback שהתקבלה פעם אחת לכל איבר במערך לפי סדר האיברים. הפונקציה לא נקראת עבור איברים שנמחקו או כאלה שאינם מכילים מידע (ראו דוגמא למטה).

הפונקציה callback

 נקראת עם שלושה פרמטרים:

  1. תוכן האיבר במערך

  2. אינדקס האיבר במערך

  3. המערך שממנו קראנו למתודה

אם העברנו את הפרמטר thisArg ל-forEach(), היא תשמש כ-this של callback.  ערך ה-this שלבסוף נצפה ע"י callback נקבע לפי החוקים הרגילים.

The range of elements processed by forEach() is set before the first invocation of callback. Elements which are appended to the array after the call to forEach() begins will not be visited by callback. If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped - see example below.

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

forEach() does not mutate the array on which it is called (although callback, if invoked, may do so).

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.


No operation for uninitialized values (sparse arrays)

const arraySparse = [1,3,,7];
let numCallbackRuns = 0;


console.log("numCallbackRuns: ", numCallbackRuns);

// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.

Converting a for loop to forEach

const items = ['item1', 'item2', 'item3'];
const copy = [];

// before
for (let i=0; i<items.length; i++) {

// after

Printing the contents of an array

Note: In order to display the content of an array in the console, you can use console.table() which will print a formatted version of the array. The following example illustrates another way of doing so, using forEach().

The following code logs a line for each element in an array:

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element);

// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9

Using thisArg

The following (contrived) example updates an object's properties from each entry in the array:

function Counter() {
  this.sum = 0;
  this.count = 0;
Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
  }, this);
  // ^---- Note

const obj = new Counter();
obj.add([2, 5, 9]);
// 3 
// 16

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked, for use as its this value.

If passing the function argument using an arrow function expression the thisArg parameter can be omitted as arrow functions lexically bind the this value.

An object copy function

The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how Array.prototype.forEach() works by using ECMAScript 5 Object.* meta property functions.

function copy(obj) {
  const copy = Object.create(Object.getPrototypeOf(obj));
  const propNames = Object.getOwnPropertyNames(obj);

  propNames.forEach(function(name) {
    const desc = Object.getOwnPropertyDescriptor(obj, name);
    Object.defineProperty(copy, name, desc);

  return copy;

const obj1 = { a: 1, b: 2 };
const obj2 = copy(obj1); // obj2 looks like obj1 now

If the array is modified during iteration, other elements might be skipped.

The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. forEach() does not make a copy of the array before iterating.

var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
  if (word === 'two') {
// one
// two
// four

Flatten an array

The following example is only here for learning purpose. If you want to flatten an array using built-in methods you can use Array.prototype.flat() (expected to be part of ES2019 and already implemented in some browsers).

 * Flattens passed array in one dimensional array
 * @params {array} arr
 * @returns {array}
function flatten(arr) {
  const result = []

  arr.forEach((i) => {
    if (Array.isArray(i)) {
    } else {
  return result

// Usage
const problem = [1, 2, 3, [4, 5, [6, 7], 8, 9]]

flatten(problem) // [1, 2, 3, 4, 5, 6, 7, 8, 9]


Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
The definition of 'Array.prototype.forEach' in that specification.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Array.prototype.forEach' in that specification.
ECMAScript 5.1 (ECMA-262)
The definition of 'Array.prototype.forEach' in that specification.
Standard Initial definition. Implemented in JavaScript 1.6.

Browser compatibility

Update compatibility data on GitHub
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
forEachChrome Full support 1Edge Full support 12Firefox Full support 1.5IE Full support 9Opera Full support YesSafari Full support 3WebView Android Full support ≤37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support 1Samsung Internet Android Full support 1.0nodejs Full support Yes


Full support  
Full support

See also