JavaScript has some methods that help us to iterate through Arrays. The two most used are foreach() and map() in Javascript. But I believe there is a lot of doubt between these two methods.
We will define each method, and where each one fits in, to try to understand better what we can do with each one:
The map() method gets a function as a parameter. This function is invoked for each Array element and, at the end, the method returns a completely new array filled with the results of the given function call.
const numbers = [5, 4, 3, 2, 1]
console.log(numbers.map(element => element * element)) //[ 25, 16, 9, 4, 1 ]
This means that it returns a new array that contains an image of each array element. It will always return the same number of items.
The forEach() method receives a function as an argument and executes it once for each Array element. However, instead of returning a new array as the map() method, it returns undefined.
const numbers = [5, 4, 3, 2, 1]
console.log(numbers.forEach(element => element * element)) //undefined
#javascript #programming #foreach