Array.forEach

Posted by Joe Enos on June 08, 2021 · 5 mins read

Definition

arr.forEach(function callback(currentValue, index, array) {
//your iterator
}[, thisArg]);

Sample Code

var arr = ["a", "b", "c"];

arr.forEach(function(x) { console.log(x); });

Using thisArg

I actually can’t think of a good purpose for this – any example I see can be done differently, and it would be clearer in my opinion. But I’m sure there are some good use cases:

var item = { sum: 0 };

[1,2,3].forEach(function(x) { this.sum += x; }, item);

console.log(item.sum); // 6

Notes

Weird things happen when you add or remove items from the array. I would recommend never modifying the array from within forEach.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Browser Requirements

Requires IE9+ or a real browser

Polyfill

if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback) {
var T, k;
if (this == null) {
throw new TypeError('this is null or not defined');
}

var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = arguments[1];
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}