forEach() method

The forEach() method calls the given function for every element in the array. It is different from the map function because map creates a copy of the original array on the basis of what you return from the map function. But foreach simply runs a function on every element. It doesn't care about what you return from the function.

Take a look at this:

const arr = [1, 2, 3, 4];arr.forEach( (value, index) => console.log(`arr[${index}] = ${value}`) );

The output is as follows:

arr[0] = 1arr[1] = 2arr[2] = 3arr[3] = 4

Clearly, when you want to just do a bunch of operations with the elements of an array, use forEach.

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.