mozilla
Your Search Results

    forEach

    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 Array.every or 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 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
    ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard Initial definition.
    Implemented in JavaScript 1.6
    ECMAScript Language Specification 6th Edition (ECMA-262) Draft  

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support (Yes) 1.5 (1.8) 9 (Yes) (Yes)
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support (Yes) (Yes) 1.0 (1.8) (Yes) (Yes) (Yes)

    See also

    Document Tags and Contributors

    Contributors to this page: Sevenspade
    Last updated by: Sevenspade,
    Hide Sidebar