JS: Array.prototype.forEach

By Xah Lee. Date: . Last updated: .
myArray.forEach(f)
  • Apply function f to every element of the array myArray.
  • Return undefined.
  • Original array is not changed.

f is given 3 args: currentElement currentIndex myArray

[1, 2, 3].forEach((x) => {
  console.log(x);
});

/*
1
2
3
*/
myArray.forEach(f, thisArg)

Use thisArg for this (binding) of f. Default to undefined.

// example of using forEach with a second argument

function ff(n) {
  // add a property key kn with value of n, to thisBinding object
  this["k" + n] = n;
  return n + 1;
}

// new object
const jj = {};

// array
const aa = [1, 2, 3];

// apply ff to each aa, using jj as thisBinding of ff
aa.forEach(ff, jj);

// jj is changed
console.log(JSON.stringify(jj) === `{"k1":1,"k2":2,"k3":3}`);

๐Ÿ’ก TIP: forEach with break

If you need to exit forEach when a condition is met, use โ€œeveryโ€ or โ€œsomeโ€.

JavaScript, Loop, Iteration

JavaScript, Map, Iteration, Reduce