JS: Array.prototype.forEach

By Xah Lee. Date: . Last updated: .

Apply function f to every element of the array myArray.

Return undefined.

Original array is not changed.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

[see JS: “this” Binding]

The function f is passed 3 args: • current_elementcurrent_indexmyArray.

const x1 = [1,2,3];

const ff = ((x) => { console.log ( x ); }) ;

x1.forEach(ff);

// prints
// 1
// 2
// 3

Example of using forEach with a second argument.

// example of using forEach with a second argument

function ff (n) {
    this["k" + n] = n; // add a property key kn with value of n, to thisBinding object
    return n+1;
}

// new object
const obj = {};

// array
const arr = [1,2,3];

// apply ff to each arr, using obj as thisBinding of ff
arr.forEach (ff, obj);

// obj is changed
console.log(obj); // { k1: 1, k2: 2, k3: 3 }

forEach that returns Array

If you need the result returned as array, use map.

[see JS: Array.prototype.map]

forEach with break

If you need to exit forEach when a condition is met, use “every” or “some”.

[see JS: Array.prototype.every]

[see JS: Array.prototype.some]

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.foreach

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth