Array.prototype.forEach()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/forEach
  • Revision title: Array.prototype.forEach()
  • Revision id: 503365
  • Created:
  • Creator: fscholz
  • Is current revision? No
  • Comment

Revision Content

{{JSRef("Global_Objects", "Array")}}

Summary

The forEach() method executes a provided function once per array element.

Syntax

arr.forEach(callback[, thisArg])

Parameters

callback
Function to execute for each element.
thisArg
Object to use as this when executing callback.

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.

Note : There is no way to stop or break a forEach loop. The solution is to use {{jsxref("Array.every")}} or {{jsxref("Array.some")}}. See example below.

forEach executes the callback function once for each array element; unlike every and some it does not return a value.

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 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

Polyfill

forEach was added to the ECMA-262 standard in the 5th edition; 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 {{jsxref("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
  };
}

Specifications

Specification Status Comment
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.foEach')}} {{Spec2('ES5.1')}} Initial definition.
Implemented in JavaScript 1.6
{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}} {{Spec2('ES6')}}  

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{ CompatVersionUnknown() }} 1.5 9 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}

See also

  • {{jsxref("Array.prototype.map()")}}
  • {{jsxref("Array.prototype.every()")}}
  • {{jsxref("Array.prototype.some()")}}

Revision Source

<div>
 {{JSRef("Global_Objects", "Array")}}</div>
<h2 id="Summary">Summary</h2>
<p>The <code><strong>forEach()</strong></code> method executes a provided function once per array element.</p>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox">
<code><em>arr</em>.forEach(<em>callback</em>[, <em>thisArg</em>])</code></pre>
<h3 id="Parameters">Parameters</h3>
<dl>
 <dt>
  <code>callback</code></dt>
 <dd>
  Function to execute for each element.</dd>
 <dt>
  <code>thisArg</code></dt>
 <dd>
  Object to use as <code>this</code> when executing <code>callback</code>.</dd>
</dl>
<h2 id="Description">Description</h2>
<p><code>forEach</code> executes the provided <code>callback</code>&nbsp;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&nbsp;<span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal;">undefined</span>.</p>
<p><code>callback</code> is invoked with <strong>three arguments</strong>:</p>
<ul>
 <li>the <strong>element value</strong></li>
 <li>the <strong>element index</strong></li>
 <li>the <strong>array being traversed</strong></li>
</ul>
<p>If a <code>thisArg</code> parameter is provided to <code>forEach</code>, it will be used as the <code>this</code> value for each <code>callback</code> invocation as if <code>callback.call(thisArg, element, index, array)</code> was called. If <code>thisArg</code> is <code>undefined</code> or <code>null</code>, the <code>this</code> value within the function depends on whether the function is in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="JavaScript/Strict_mode">strict mode</a> or not (passed value if in strict mode, global object if in non-strict mode).</p>
<p>The range of elements processed by <code>forEach</code> is set before the first invocation of <code>callback</code>. Elements which are appended to the array after the call to <code>forEach</code> begins will not be visited by <code>callback</code>. If existing elements of the array are changed, or deleted, their value as passed to <code>callback</code> will be the value at the time <code>forEach</code> visits them; elements that are deleted are not visited.</p>
<div class="note">
 <strong>Note :</strong> There is no way to stop or break a forEach loop. The solution is to use {{jsxref("Array.every")}} or {{jsxref("Array.some")}}. See example below.</div>
<p><code>forEach</code> executes the <code>callback </code>function once for each array element; unlike <code>every <code>and some&nbsp;</code></code>it does not return a value.</p>
<h2 id="Examples">Examples</h2>
<h3 id="Printing_the_contents_of_an_array">Printing the contents of an array</h3>
<p>The following code logs a line for each element in an array:</p>
<pre class="brush:js">
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
</pre>
<h3 id="Breaking_a_loop">Breaking a loop</h3>
<p>The following code logs the content of an array and stops when it reaches a value higher than the given THRESHOLD.</p>
<pre class="brush: js">
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 &gt;= 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 &gt;= THRESHOLD) {
        return true;
    }

    return false;
});
console.log("res:", res);
// logs:
// element: 5
// element: 2
// element: 16
// res: true
</pre>
<h3 id="An_object_copy_function">An object copy function</h3>
<p>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 <code>Array.prototype.forEach</code> works. It uses a couple of new ECMAScript 5 Object.* functions.</p>
<pre class="brush: js">
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
</pre>
<h2 id="Polyfill">Polyfill</h2>
<p><code>forEach</code> was added to the ECMA-262 standard in the 5th edition; 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 <code>forEach</code> in implementations which do not natively support it.</p>
<pre class="brush:js">
if (!Array.prototype.forEach) {
&nbsp;&nbsp;&nbsp; Array.prototype.forEach = function (fn, scope) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 'use strict';
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var i, len;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (i = 0, len = this.length; i &lt; len; ++i) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (i in this) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fn.call(scope, this[i], i, this);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; };
}
</pre>
<p>An algorithm 100% true to the ECMA-262, 5th edition can be seen below:</p>
<p>This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming <code>Object</code> and <code>TypeError</code> have their original values and that <code>callback.call</code> evaluates to the original value of {{jsxref("Function.prototype.call")}}.</p>
<pre class="brush: js">
// 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) {

&nbsp; Array.prototype.forEach = function forEach(callback, thisArg) {
&nbsp;&nbsp;&nbsp; 'use strict';
&nbsp;&nbsp;&nbsp; var T, k;

&nbsp;&nbsp;&nbsp; if (this == null) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new TypeError("this is null or not defined");
&nbsp;&nbsp;&nbsp; }

&nbsp;&nbsp;&nbsp; var kValue,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 1. Let O be the result of calling ToObject passing 
        //    the |this| value as the argument.
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; O = Object(this),

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 2. Let lenValue be the result of calling the 
        //    Get internal method of O with the argument "length".
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // 3. Let len be ToUint32(lenValue).
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; len = O.length &gt;&gt;&gt; 0; // Hack to convert O.length to a UInt32

&nbsp;&nbsp;&nbsp; // 4. If IsCallable(callback) is false, throw a TypeError exception.
&nbsp;&nbsp;&nbsp; // See: http://es5.github.com/#x9.11
&nbsp;&nbsp;&nbsp; if ({}.toString.call(callback) !== "[object Function]") {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new TypeError(callback + " is not a function");
&nbsp;&nbsp;&nbsp; }

&nbsp;&nbsp;&nbsp; // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
&nbsp;&nbsp;&nbsp; if (arguments.length &gt;= 2) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; T = thisArg;
&nbsp;&nbsp;&nbsp; }

&nbsp;&nbsp;&nbsp; // 6. Let k be 0
&nbsp;&nbsp;&nbsp; k = 0;

&nbsp;&nbsp;&nbsp; // 7. Repeat, while k &lt; len
&nbsp;&nbsp;&nbsp; while (k &lt; len) {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // a. Let Pk be ToString(k).
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //&nbsp;&nbsp; This is implicit for LHS operands of the in operator
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // b. Let kPresent be the result of calling the 
      //   HasProperty internal method of O with argument Pk.
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //&nbsp;&nbsp; This step can be combined with c
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // c. If kPresent is true, then
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (k in O) {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // i. Let kValue be the result of calling the
        //    Get internal method of O with argument Pk.
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; kValue = O[k];

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // ii. Call the Call internal method of callback 
        //     with T as the this value and
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // argument list containing kValue, k, and O.
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; callback.call(T, kValue, k, O);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // d. Increase k by 1.
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; k++;
&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; // 8. return undefined
&nbsp; };
}
</pre>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.foEach')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition.<br />
    Implemented in JavaScript 1.6</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
 <table class="compat-table">
  <tbody>
   <tr>
    <th>Feature</th>
    <th>Chrome</th>
    <th>Firefox (Gecko)</th>
    <th>Internet Explorer</th>
    <th>Opera</th>
    <th>Safari</th>
   </tr>
   <tr>
    <td>Basic support</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>1.5</td>
    <td>9</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>{{ CompatVersionUnknown() }}</td>
   </tr>
  </tbody>
 </table>
</div>
<div id="compat-mobile">
 <table class="compat-table">
  <tbody>
   <tr>
    <th>Feature</th>
    <th>Android</th>
    <th>Chrome for Android</th>
    <th>Firefox Mobile (Gecko)</th>
    <th>IE Mobile</th>
    <th>Opera Mobile</th>
    <th>Safari Mobile</th>
   </tr>
   <tr>
    <td>Basic support</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>{{ CompatVersionUnknown() }}</td>
    <td>{{ CompatVersionUnknown() }}</td>
   </tr>
  </tbody>
 </table>
</div>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
 <li>{{jsxref("Array.prototype.map()")}}</li>
 <li>{{jsxref("Array.prototype.every()")}}</li>
 <li>{{jsxref("Array.prototype.some()")}}</li>
</ul>
Revert to this revision