JavaScript — When to use .map and .forEach

JavaScript can be confusing sometimes, especially when you don’t know the correct use of some predefined methods. Using these methods in a wrong way can sometimes hamper your application’s performance or worst, can give your seniors an opportunity of judging your coding knowledge!
So let's take a look at .map and .forEach in terms of syntax, similarities, differences, and the correct way of using them.
.map and .forEach (Similarities)

Map and forEach, both are used to iterate over an array. They are looping methods.
It provides a callback function that runs on every element in an array. The callback takes 3 arguments viz the element, index of the element, and the array the method was called upon.
Both the methods (map and forEach), do not change the original array i.e numbers1 and number2 irrespective of any operations that are performed within its callback function.
.map & .forEach (Differences)
- The main difference lies in its return type.
The return type of map is an Array whereas the return type of forEach is undefined.
The length of the returned array from the .map is always equal to the length of the original array
numbers1.length === newNumberArray1.length; // true
typeof newNumberArray2; //undefined - Synchronous Asynchronous game!
.forEach expects a synchronous function. forEach does not wait for promises. NEVER call async-await functions inside a forEach loop.
Right way of using .map and .forEach
- If you simply want to loop over an array, always use a forEach method.
If you want to modify the array, perform operations on any specific or all the elements of the array, always use a map function since the modified array will be returned by the map.

2. If you want to write async code, always use .map !
These are the few basic things that you need to remember while using the above two methods. Hope this article helped you in an expected way 🐱🏍!
Thanks for reading🐱👤