JavaScript Array forEach

The JavaScript Array forEach method executes a user-defined function for each element of an array.


array.forEach(callback [, contextObject])


The callback function to execute for each element
Object to be used as a context for the callback function


The JavaScript ArrayforEach method iterates over and applies the callback function to each element of an array.

The callback function is invoked with three arguments: the value of the element, the index of the element and the Array object being traversed.

Cross-browser Array forEach

For browsers that don't support the Array forEach method, here's an alternative implementation:

 * Copyright (c) Mozilla Foundation
 * This code is available under the terms of the MIT License
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();

        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
      , this[i], i, this);

See also

If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.

Copyright © 2010-2013 Dive Into JavaScript