A Complete Guide: JavaScript Array forEach().

JavaScript , , 0 Comments
A Complete Guide JavaScript Array forEach

The JavaScript array forEach method accepts the callback method and executes it once for each element of the array, in order to skip non-existent entries in sparse arrays.

Here is a quick and simple example.

var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
  console.log(element);
});

// expected output: "a"
// expected output: "b"
// expected output: "c"

Although I only used one argument above. But, it takes three arguments: The value of each entry, the index of that entry, and a reference to the array you’re iterating over.

currentValue The current element being processed in the array.

index (Optional) The index of the current element being processed in the array.

array (Optional) The array forEach() was called upon.

thisArg (Optional) Value to use as this when executing callback.

Warninig: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Performance

If you’re worried about the runtime cost of making a function call for JavaScript forEach array entry, don’t be.

The performance of looping through a 100-entry array both with and without calling a function. Without the function call, IE6 looped through the array ~4,500 times in a second (that’s 450,000 loop iterations/second). With the function, it managed ~2,000 times a second (200,000 loop iterations/second). So while that’s a big relative difference (56% slower!), in real terms it falls into fuggedaboudit territory: 2.78 microseconds of overhead. You heard me, microseconds. That’s 0.00278 milliseconds.

source

Examples

#1 No operation for uninitialized values (sparse arrays)

const arraySparse = [1,3,,7];
let numCallbackRuns = 0;

arraySparse.forEach(function(element){
  console.log(element);
  numCallbackRuns++;
});

console.log("numCallbackRuns: ", numCallbackRuns);

// 1
// 3
// 7
// numCallbackRuns: 3

As you can see the missing value between 3 and 7 didn’t invoke the callback function. in the above example.

#2 Converting a for loop to forEach

Here is the example of the same iteration on for loop and forEach

const items = ['item1', 'item2', 'item3'];
const copy = [];

// simple for loop
for (let i=0; i<items.length; i++) {
  copy.push(items[i]);
}

// using the forEach function 
items.forEach(function(item){
  copy.push(item);
});

#3 If the array is modified during iteration

The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. forEach() does not make a copy of the array before iterating.

var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
  console.log(word);
  if (word === 'two') {
    words.shift();
  }
});
// one
// two
// four

#4 Flatten an array

function flatten(arr) {
  const result = []

  arr.forEach((i) => {
    if (Array.isArray(i)) {
      result.push(...flatten(i))
    } else {
      result.push(i)
    }
  })
  
  return result
}

// Usage
const problem = [1, 2, 3, [4, 5, [6, 7], 8, 9]]

flatten(problem) // [1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want to flatten an array using built-in methods you can use Array.prototype.flat()

Support

Unless you’re supporting obsolete browsers like IE8 (which StatCounter shows it less than 1% market share as in 2019), you can happily use forEach in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling forEach is easily done (search for “es5 shim” for several options).

forEach has the benefit that you don’t have to declare indexing and value variables in the containing scope, as they’re supplied as arguments to the iteration function, and so nicely scoped to just that iteration.

Method
forEach()Yes9.01.5YesYes

Spread the love
  • 1
    Share

Leave a Reply

avatar
  Subscribe  
Notify of