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

3 min read
Last updated: Oct 13, 2024

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 an 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.

Any thoughts, let's discuss on twitter

Sharing this article is a great way to educate others like you just did.



If you’ve enjoyed this issue, do consider subscribing to my newsletter.


Subscribe to get more such interesting content !

Tech, Product, Money, Books, Life. Discover stuff, be inspired, and get ahead. Box Piper is on Twitter and Discord. Let's Connect!!

To read more such interesting topics, let's go Home

More Products from the maker of Box Piper:

Follow GitPiper Instagram account. GitPiper is the worlds biggest repository of programming and technology resources. There is nothing you can't find on GitPiper.

Follow SharkTankSeason.com. Dive into the riveting world of Shark Tank Seasons. Explore episodes, pitches, products, investment details, companies, seasons and stories of entrepreneurs seeking investment deals from sharks. Get inspired today!.


Scraper API

More Blogs from the house of Box Piper: