Codementor Events

JavaScript Array Methods: .forEach - The Functional for of loop

Published May 16, 2019Last updated May 26, 2019
JavaScript Array Methods: .forEach - The Functional for of loop

Meet Arrayโ€‹.prototypeโ€‹.forโ€‹Each().

It's purpose is to execute the code you provide it over each item of the array: essentially a loop.

Here's its definition:

01-definition.png

Let's explain it below. ๐Ÿ˜‰

It's Parameters

forEach accepts up to two parameters:

  • the callback function, which is executed over each item of the array
  • the thisArg (optional), which changes the value of this inside of the callback function

Now, a deeper look at each one. ๐Ÿ‘‡

1) The callback function

The method that is called on each element of the array. It takes up to three parameters:

  • currentValue: current item of the array, ๐ŸŽ on the first iteration
  • index (optional): index of the current item, 0 on the first iteration
  • array (optional): the whole array, the same on all iterations

02-00-callback-function.png

The index Parameter

The index parameter is optional. It is handy when the logic depends on the item's position in the array.

02-01-index-param.png

The array Parameter

The last parameter is array. It is the value of the whole array at the beginning of the execution of the callback method.
Handy : It is useful when you have a generic method that you pass to forEach which requires access to the array. The method being generic you cannot know in advance the array it will be called on. Which also mean you cannot rely on the closure as it is unknown.

Thus the array parameter in that case is your only option to get access to the current array.

See this Stackoverflow response reply from redneb for more info.

2) The thisArg Parameter

Overrides the this keyword value inside the callback function.

By default this would refer to the window object, and it will be overridden by the value you pass it.

03-thisArg.png

My Usage of forEach

I generally use it when I want to apply a side-effect to some object or another array. (I try avoiding side-effect as much I can.)

Example

In this case we have a list of emojis and the corresponding list of names. We want to create an object where the key will be the name and the value will contain the emoji.

The two arrays are sorted the same way: at any given index items from both array correspond.

04-use-case.png

Note that fruitMap is created before calling forEach on fruitEmojis. And we update the object during the executions of addKeyPairToFruitMap.

Information To Consider

Before using the forEach methods on arrays here's some information worth knowing.

1) Returns undefined, thus NOT Chainable

The forEach array method always returns undefined, thus it is NOT chainable. Which means that in a call chain, it can only be placed at the end.

05-not-chainable.png

2) Callback Function Can Modify Original Array

We can add/remove/update items from the array from inside the callback function.

Addition

Adding does NOT affect the items for the call: only the items initially present are processed.

But after the execution we see that it was affected.

06-adding-to-original.png

Deletion

Deletion DOES affect the number of items for the call. If the next planned item is removed it will not be processed.

07-removing-from-original.png

Modification

Modification DOES affect the items themselves for the call, but not the count. If we modify the next planned item, this modification is available when it is then processed.

Note that the forth item is due to this statement the following statement which adds an item to the array on the last execution: fruitEmojis[index + 1] = "AAAAAARH!";.

08-modifying-original-array-edit.png

3) Cannot Be Stopped

You cannot stop the execution or "break the loop" when calling the forEach method.

If you are trying to stop the execution you should probably use a different array method (eg. find, filter, reduce, some, includes) or use a for-loop instead.

Conclusion

I hope this article about the forEach method has brought you value. ๐Ÿ™‚ It will be part of a series on JavaScript arrays, so stay tuned for the next one! ๐ŸŽ‰

Until then, happy coding! ๐Ÿ˜Ž

Discover and read more posts from Cedric Poilly
get started
post commentsBe the first to share your opinion
Show more replies