JavaScript Array forEach method

When provided with an array, the forEach() function is responsible for calling a function for every item in the given array. However, it is worth noting that this method does not execute when no elements exist.

forEach() syntax

The syntax for the forEach() is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>array.forEach(function(currentValue, index, arr), thisValue)</pre>
</div>

Parameters

Following the above syntax, here are the essential parameters for the forEach() function. We will examine each of them and demonstrate where and how it is used.

function()

– It is required and denotes the function running for every element in the array provided.

currentValue

-It is also a required parameter and holds the value of the present item in the array

index

– it is an optional parameter holding the current elements’ index

arr

– arr is an optional parameter representing the array to which the current element belongs

thisValue

– Despite this parameter being undefined by default, it is also optional. It holds the value provided to the function and is commonly denoted as “this” value.

Return Value

The forEach() return value is undefined.

What are the Optional parameters?

Here, we will explore the two optional parameters which comprise Index, & Array.

Index

Now let’s move on to the optional arguments. The first is the “index” argument, which represents the element’s index number. We may see the index number of an element by including it as a second parameter:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>numVars.forEach((val, idx) => {
    console.log('Index: ' + idx + ' Value: ' + val);
});</pre>
</div>

Array

The array itself is the array argument. It is also optional and can be employed in a variety of operations as needed. Otherwise, if we call it, it will be printed as many times as the number of array elements:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>numVars.forEach((num, index, arr) => {
    console.log(arr);
});</pre>
</div>

Example: Calling a function for each element in a List

In this example, we demonstrate how each element in a list is processed by the codeFunction function.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const compCompanies = ["IBM", "Google", "Facebook"];
compCompanies.forEach(codeFunction);

 
function codeFunction(item, index) {
  text += index + ": " + item;
 console.log(text)
}</pre>
</div>

Example: Representation of element Multiplication

The demonstration below elucidates the concept of multiplying elements.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const numsArray = [77, 56, 24, 16];
numsArray.forEach(calcFunction)

function calcFunction(val, idx, numsArr) {
  numsArr[idx] = val * 10;
}</pre>
</div>

Example: Sum computation

Here, we illustrate the concept of sum computation.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>let sumVal = 0;
const numsArray = [77, 56, 24, 16];
numsArray.forEach(calcFunction);

function calcFunction(val) {
  sumVal += val;
}</pre>
</div>

Array.prototype.forEach()

For individual elements in the provided array, the forEach() function executes the given function exactly once. Here is a demo to illustrate this.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const arrChars = ['x', 'y', 'z'];

arrChars.forEach(item => console.log(item));</pre>
</div>

The comprehensive syntax covering the arrow function, the callback function, and the inline callback function is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)

// Inline callback function
forEach(function(element) { /* … */ })
forEach(function(element, index) { /* … */ })
forEach(function(element, index, array){ /* … */ })
forEach(function(element, index, array) { /* … */ }, thisArg)</pre>
</div>

Description

For each entry in an array, in ascending index order, forEach() calls the callbackFn function supplied once. When an index property is uninitialized or deleted, it is not called.

Three arguments are provided when calling callbackFn:

  • the element’s value
  • the element’s index
  • the traversing Array object

ForEach() will use the thisArg parameter as the callback’s this value if one is passed to it. The thisArg value that callbackFn can ultimately observe is determined using the standard guidelines for determining the observation by a function.

Before the initial callbackFn is made, the range of elements that forEach() will process is configured. CallbackFn won’t visit elements assigned to already visited indexes or indexes outside of the range.

The value given to callbackFn will reflect the value when forEach() visits the array’s existing items if they are updated or deleted; elements that are deleted before being visited are not visited. Later elements will be skipped if elements that have already been visited are removed (using shift(), for example) during the iteration.

Concurrent alteration of the kind mentioned in the preceding sentence typically results in difficult-to-understand code and should be avoided in general except in exceptional cases.

For each array element, forEach() calls the callbackFn function once; unlike map() and reduce(), it never returns a value and cannot be chained. The common use case is executing side effects at the conclusion of a chain. The array that forEach() is executed on does not change. CallbackFn may do this, though. Other than exception throwing, there is no other method to end or break a forEach() loop.

The function’ forEach()’ is not the appropriate tool if you require this behavior. Early termination is possible through:

  • Array.prototype.every()
  • Array.prototype.some()
  • A simple for loop
  • Array.prototype.find()
  • Array.prototype.findIndex()
  • A for…of / for…in loops

In order to decide whether more iterations are necessary, the array methods every(), some(), find(), and findIndex() test the array members using a predicate yielding a truthy value. A synchronous function is what forEach anticipates. Further, forEach doesn’t hold out for promises. Be mindful of the repercussions when utilizing promises (or async functions) as forEach callback.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const ratings = [8, 7, 8];
let sum = 0;

const sumFunction = async (a, b) => a + b;

ratings.forEach(async (rating) => {
  sum = await sumFunction(sum, rating);
});

console.log(sum);
// Naively expected output:
// Actual output: 0</pre>
</div>

Example: There isn’t a method for uninitialized values (sparse arrays)

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const arrSparse = [1, 3, /* empty */, 7];
let numberOfCallbackRuns = 0;

arrSparse.forEach((val) => {
  console.log({ val });
  numberOfCallbackRuns ++;
});

console.log({ numberOfCallbackRuns });

// 1
// 3
// 7
// numberOfCallbackRuns: 3
// comment: According to the observation above, the missing value between 3 and 7 didn't invoke the callback function.</pre>
</div>

Example: Converting a for loop to forEach

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const items = ['item1', 'item2', 'item3'];
const copyItems = [];

// before
for (let i = 0; i < items.length; i++) {
  copyItems.push(items[i]);
}

// after
items.forEach((item) => {
  copyItems.push(item);
});</pre>
</div>

Example: How to print an array’s contents

Using console.table(), which prints a formatted representation of the array, you can display the contents of an array in the console. An alternative strategy is demonstrated in the example below by using forEach(). The code below creates a line in the log for each entry in an array:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const logArrElements = (val, idx, array) => {
  console.log(`arr[${idx}] = ${val}`);
};

//Hope you can realize that the second index is skipped since there is no item at that position in the array.
[5, 8 , 12].forEach(logArrElements);
// logs:
// arr[0] = 5
// arr[1] = 8
// arr[3] = 12</pre>
</div>

How to use the thisArg

The (artificial) example below modifies an object’s attributes using each entry in the array:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>class Counter {
  constructor() {
    this.sum = 0;
    this.count = 0;
  }
  add(array) {
    // Only function expressions will have their binding
    array.forEach(function countEntry(entry) {
      this.sum += entry;
      ++this.count;
    }, this);
  }
}

const obj = new Counter();
obj.add([5, 8, 12]);
console.log(obj.count); // 3
console.log(obj.sum); // 25
</pre>
</div>

The callback receives the thisArg parameter (this), which is supplied to forEach()each time it is called. It serves as this value in the callback.

The thisArg parameter could be skipped if the callback function was sent an arrow function expression because all arrow functions lexically bind this value.

A function for object copy

The code that follows makes a clone of the specified object. There are various approaches to making a replica of an object. The following is only one example of how the Array.prototype.forEach() method in ECMAScript 5 works by utilizing the Object.* meta property functions.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const valCopy = (obj) => {
  const valCopy = Object.create(Object.getPrototypeOf(obj));
  const propNames = Object.getOwnPropertyNames(obj);
  propNames.forEach((name) => {
    const description = Object.getOwnPropertyDescriptor(obj, name);
    Object.defineProperty(copy, name, description);
  });
  return valCopy;
};

const firstObj = { a: 1, b: 2 };
const secondObj = copy(firstObj); // secondObj looks like firstObj now</pre>
</div>

Iteratively altering the array

The example that follows logs 1, 2, and 4. The initial entry of the entire array is shifted off when the entry holding the value two is reached, which causes all other entries to move up one position. Three will be skipped because element four is now earlier in the array. Before iterating, forEach() does not create a copy of the array.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
  if (word === 'two') {
    words.shift(); //'one' will delete from array
  }
}); // one // two // four

console.log(words); // ['two', 'three', 'four']</pre>
</div>

Making an array flat

The following illustration is only provided for educational purposes. Using built-in methods, you can use Array.prototype.flat() to flatten an array.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>const flatten = (arr) => {
  const rsVal = [];
  arr.forEach((k) => {
    if (Array.isArray(k)) {
      rsVal.push(...flatten(k));
    } else {
      result.push(k);
    }
  });
  return rsVal;
}

// use case
const valsNested = [4, 5, 6, [7, 8, [9, 10], 11, 12]];
console.log(flatten(valsNested)); // [4, 5, 6, 7, 8, 9, 10, 11, 12]</pre>
</div>

Conclusion

One of the many methods for iterating through an array is the forEach method in JavaScript. Depending on what you’re doing and the features of each strategy, it’s up to you to choose which one to use. In contrast to the conventional “for loop,” the forEach method employs a function to iterate through arrays.

The following parameters are passed to forEach method along with a callback function for each entry of an array:

  • Current Value: The value of the currently selected array element.
  • Index: The index of the currently selected element.
  • The array object to which the current member belongs in the array.

Finally, except for Internet Explorer 8 and earlier, all browsers support the Array.forEach method.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *