JS: Array.prototype.forEach

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

f is passed 3 args: currentElement, currentIndex, xArray.

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

/*
1
2
3
*/
xArray.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 this-binding object
 this["k" + n] = n;
}

// new object
const jj = {};

// array
const xarr = [1, 2];

// apply ff to each xarr, using jj as this-binding of ff
xarr.forEach(ff, jj);

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

🟒 tip: forEach with break

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