JavaScript Array forEach() Method - How to Iterate an Array with Best Practices in 2020

Subscribe to my newsletter and never miss my upcoming articles

The forEach() method is a standard built-in method which executes a given function once for an array element.

Without mutating the array, array.forEach() method iterates in ascending order.

Basic Example

const arr = ['box', 'piper', 'world'];

arr.forEach(ele => console.log(ele));

// expected output: "box"
// expected output: "piper"
// expected output: "world"

Basic Syntax

array.forEach(callback [, thisArg])

forEach() calls a given callback function once for each element in an array in ascending order. The second optional argument is the value of this set in the callback. Index properties that have been deleted or are uninitialized are never invoked by forEach().

const arr = ['box', 'piper', 'world'];

function iterateArr(name) {
  console.log(name);
}

arr.forEach(iterateArr);

// expected output: "box"
// expected output: "piper"
// expected output: "world"

In the above example, iterateArr is the callback function.

arr.forEach(iterateArr) executes iterateArr function for every item in the array arr.

The invocation of iterateArr(name) function are as follows:

  • iterateArr('box')
  • iterateArr('piper')
  • iterateArr('world')

Example with an iterated element index

const arr = ['box', 'piper', 'world'];

function iterateArr(name, index) {
  console.log(`${name} has index ${index}`);
}

arr.forEach(iterateArr);

// expected output: "box has index 0"
// expected output: "piper has index 1"
// expected output: "world has index 2"

The invocation of iterateArr(name, index) function are as follows:

  • iterateArr('box', 0)
  • iterateArr('piper', 1)
  • iterateArr('world', 2)

Syntax with an iterated element index

array.forEach(callback(item [, index [, array]]))

As shown in the above syntax, array.forEach(callback) executes the callback function with 3 arguments:

  • the current iterated item,
  • the index of the iterated item and
  • the array instance itself.

Example to Access the array inside the callback

const arr = ['box', 'piper', 'world'];

/*
The 3rd parameter in iterateArr function 
is the array on which forEach() method 
was called on.
*/

function iterateArr(name, index, arr) {
  console.log(item);
  if (index === arr.length - 1) {
    console.log('No further elements in an arr');
  }
}

arr.forEach(iterateArr);

// expected output: "box"
// expected output: "piper"
// expected output: "world"
// expected output: "No further elements in an arr"

Examples with an Uninitialized Spaces

const sparsedArray = ["box", , "piper"];
sparseArray.length; 
//  expected output: 3

sparsedArray.forEach((item) => {
  console.log(item);
}); 
//  expected output: box
//  expected output: piper

Normally, the length property of an array specifies the number of elements in the array. If the array is sparse, the value of the length property is greater than the number of elements. A sparse array is one, in which the elements do not have contiguous indexes starting at 0.

Break a forEach() loop

Only by throwing an exception, we can stop or break a forEach() loop. For early termination of an array iteration, forEach() is not used for. It can easily be done by other array methods like:

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

forEach() and Promises

forEach() does not wait for promises and expects a synchronous function.

let randomNumbers = [1, 2];
let randomNumbersSum = 0;

async function sumIt(i, j){
  return i + j
}

randomNumbers.forEach(async (randomNumber) => {
  randomNumbersSum = await sumIt(sum, randomNumber)
})

console.log(randomNumbersSum)
// Naively expected output: 3
// Actual output: 0

Ending Note

array.forEach(callback) method is an efficient way to iterate over all the array items, using callback, items, indexes and even pass a complete array to the callback.

To read extensively about JavaScript Array, MDN DOCS is the only bible which has all the updated information.

To read interesting topics, follow and read BoxPiper blog.

Tech, Product, Money, Books, Life. Box Piper to serve you faster, easier and superior knowledge.

No Comments Yet