Summary
Executes a provided function once per array element.
Method of Array |
|
|---|---|
| Implemented in | JavaScript 1.6 |
| ECMAScript Edition | ECMAScript 5th Edition |
Syntax
array.forEach(callback[, thisArg])
Parameters
-
callback - Function to execute for each element.
-
thisArg -
Object to use as
thiswhen executingcallback.
Description
forEach executes the provided callback once for each element of the array with an assigned value. It is not invoked for indexes which have been deleted or which have been initialized to undefined.
callback is invoked with three arguments:
- the element value
- the element index
- the array being traversed
If a thisArg parameter is provided to forEach, it will be used as the this value for each callback invocation as if callback.call(thisArg, element, index, array) was called. If thisArg is undefined or null, the this value within the function depends on whether the function is in strict mode or not (passed value if in strict mode, global object if in non-strict mode).
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 are not visited.
Examples
Printing the contents of an array
The following code logs a line for each element in an array:
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9
Breaking a forEach loop
The following code logs the content of an array and stops when it reaches a value higher than the given THRESHOLD.
var THRESHOLD = 12;
var v = [5, 2, 16, 4, 3, 18, 20];
var res;
res = v.every(function(element, index, array) {
console.log("element:", element);
if (element >= THRESHOLD) {
return false;
}
return true;
});
console.log("res:", res);
// logs:
// element: 5
// element: 2
// element: 16
// res: false
res = v.some(function(element, index, array) {
console.log("element:", element);
if (element >= THRESHOLD) {
return true;
}
return false;
});
console.log("res:", res);
// logs:
// element: 5
// element: 2
// element: 16
// res: true
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. This one is just one of them here to explain how Array.prototype.forEach works. It uses a couple of new ECMAScript 5 Object.* functions.
function copy(o){
var copy = Object.create( Object.getPrototypeOf(o) );
var propNames = Object.getOwnPropertyNames(o);
propNames.forEach(function(name){
var desc = Object.getOwnPropertyDescriptor(o, name);
Object.defineProperty(copy, name, desc);
});
return copy;
}
var o1 = {a:1, b:2};
var o2 = copy(o1); // o2 looks like o1 now
Compatibility
forEach is a recent addition to the ECMA-262 standard; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of forEach in implementations which do not natively support it.
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fn, scope) {
'use strict';
var i, len;
for (i = 0, len = this.length; i < len; ++i) {
if (i in this) {
fn.call(scope, this[i], i, this);
}
}
};
}
An algorithm 100% true to the ECMA-262, 5th edition can be seen below:
This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values and that callback.call evaluates to the original value of Function.prototype.call.
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(callback, thisArg) {
'use strict';
var T, k;
if (this == null) {
throw new TypeError("this is null or not defined");
}
var kValue,
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
O = Object(this),
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
len = O.length >>> 0; // Hack to convert O.length to a UInt32
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if ({}.toString.call(callback) !== "[object Function]") {
throw new TypeError(callback + " is not a function");
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length >= 2) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | 1.5 | 9 | (Yes) | (Yes) |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | ? |
Based on Kangax's compat tables
Mozilla Developer Network