+ 5
Which is Best between forEach() and map() in js ?
forEach() — executes a provided function once for each array element. map() — creates a new array with the results of calling a provided function on every element in the calling array. Then , Which is Best between forEach() and map() in js ?
2 Respostas
+ 1
It depends on what you want to do. As you mentioned, map() creates a new array with the results of a function, so it is useful when you want to do some operations on the elements of an array and then get a new array with the results. For example, if you want a new array with the squares of the elements of an array
[1, 2, 3, 4].map(n => n * n) // returns [1, 4, 9, 16]
Use forEach() when you want to use the elements of an array for some purpose, but the result is not an array. For example,
let sum = 0;
[1, 2, 3, 4].forEach(n => { sum += n; })
// sum will be 10 now
+ 3
Thanks