forEach() Vs Map() In JavaScript πŸ€”

Suhail Roushan πŸš€
2 min readOct 9, 2022

--

ForEach()

The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

Always remember that it doesn’t return anything and if you try to get the value it will be undefined.

Map()

The map method returns a new array by applying the callback function on each element of an array

it creates a new array with the results of calling a function for every array element. Hence map() method relies on immutability. Also, map() does not execute/call the function for those array elements without values.

Differences Between ForEach() and Map()

1. The returning value

2. Ability to chain other methods

3. Mutability

4. Performance Speed

Final Thoughts

As always, the choice between map() and forEach() will depend on your use case. If you plan to change, alternate, or use the data, you should pick map(), because it returns a new array with the transformed data.

But, if you won’t need the returned array, don’t use map() - instead use forEach() or even a for loop.

--

--

Suhail Roushan πŸš€

⭐ Software Engineer at T-Works πŸ§‘β€πŸ’» Full Stack Web Developer πŸŽ“ CS.CODE.IN Fellow '21 πŸ’‘ Startup Tech Innovator πŸ‘¨β€πŸŽ¨ UI/UX Designer πŸ€– Automation