Array.prototype.forEach()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/forEach
  • Revision title: Array.forEach
  • Revision id: 417499
  • Created:
  • Creator: Sheppy
  • Is current revision? No
  • Comment Moved From JavaScript/Reference/Global_Objects/Array/forEach to Web/JavaScript/Reference/Global_Objects/Array/forEach

Revision Content

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

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

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) {
    for(var i = 0, len = this.length; i < len; ++i) {
      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.

// 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 ) {

    var T, k;

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

    // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    var 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).
    var 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 ( thisArg ) {
      T = thisArg;
    }

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

    // 7. Repeat, while k < len
    while( k < len ) {

      var kValue;

      // 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 ( Object.prototype.hasOwnProperty.call(O, k) ) {

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

{{ CompatibilityTable() }}

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

Based on Kangax's compat tables

See also

Array.map

Revision Source

<h2 id="Summary">Summary</h2>
<p>Executes a provided function once per array element.</p>
<table class="standard-table">
  <thead>
    <tr>
      <th class="header" colspan="2">Method of <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="JavaScript/Reference/Global_Objects/Array"><code>Array</code></a></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Implemented in</td>
      <td>JavaScript 1.6</td>
    </tr>
    <tr>
      <td>ECMAScript Edition</td>
      <td>ECMAScript 5th Edition</td>
    </tr>
  </tbody>
</table>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox">
<code><em>array</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="/en-US/docs/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>
<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="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="Compatibility">Compatibility</h2>
<p><code>forEach</code> 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 <code>forEach</code> in implementations which do not natively support it.</p>
<pre class="brush:js">
if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i &lt; len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}
</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 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call" title="JavaScript/Reference/Global Objects/Function/call">Function.prototype.call</a></code>.</p>
<!-- DO_NOT_MODIFY_THE_FOLLOWING_CODE_IN_ANY_WAY -->
<pre class="brush: js">
// 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 ) {

    var T, k;

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

    // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    var 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).
    var len = O.length &gt;&gt;&gt; 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 ( thisArg ) {
      T = thisArg;
    }

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

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

      var kValue;

      // 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 ( Object.prototype.hasOwnProperty.call(O, k) ) {

        // 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
  };
}
</pre>
<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>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
      </tr>
    </tbody>
  </table>
</div>
<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat tables</a></p>
<h2>See also</h2>
<p><a class="internal" href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map">Array.map</a></p>
Revert to this revision