mozilla

Revision 573693 of Array.prototype.forEach()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/forEach
  • Revision title: Array.prototype.forEach()
  • Revision id: 573693
  • Created:
  • Creator: ewelander
  • 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
Value 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 elided. However, it is executed for values which are present but have the value 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 passed to callback when invoked, for use as its this value.  Otherwise, the value undefined will be passed for use as its this value.  The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

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.  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")}}.

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisArg, t[i], i, t);
    }
  };
}

Specifications

Specification Status Comment
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}} {{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() }} {{CompatGeckoDesktop("1.8")}} 9 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{CompatGeckoMobile("1.8")}} {{ 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>
  Value 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 elided. However, it is executed for values which are present but have the value undefined.</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 passed to <code>callback</code> when invoked, for use as its <code>this</code> value.&nbsp; Otherwise, the value <code>undefined</code> will be passed for use as its <code>this</code> value.&nbsp; The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</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.&nbsp; 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">
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length &gt;&gt;&gt; 0;
    if (typeof fun&nbsp;!== "function")
      throw new TypeError();

    var thisArg = arguments.length &gt;= 2 ? arguments[1] : void 0;
    for (var i = 0; i &lt; len; i++)
    {
      if (i in t)
        fun.call(thisArg, t[i], i, t);
    }
  };
}
</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.forEach')}}</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>{{CompatGeckoDesktop("1.8")}}</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>{{CompatGeckoMobile("1.8")}}</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