+ 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 ?

4th Sep 2020, 1:03 PM
Prathamesh Thorat
Prathamesh Thorat - avatar
2 ответов
+ 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
4th Sep 2020, 2:10 PM
XXX
XXX - avatar
+ 3
Thanks
4th Sep 2020, 4:01 PM
Prathamesh Thorat
Prathamesh Thorat - avatar