JavaScript Array forEach() Method - How to Iterate an Array with Best Practices in 2020
Tags: javascript, arrays, loops, mdn
Published: 2021-01-26 19:45:42

## 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

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

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

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

## Basic Syntax

```javascript
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().

```javascript
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

```javascript
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

```javascript
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

```javascript
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

```javascript
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.`

# <u>Break a forEach() loop</u>

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()

# <u>forEach() and Promises</u>

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

```javascript
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, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" rel="noopener" target="_blank"> MDN DOCS </a>is the only bible which has all the updated information. 

To read more such interesting topics, follow and read <a href="https://boxpiper.com/">BoxPiper blog</a>.