JavaScript — When to use .map and .forEach

Krantibrid
2 min readSep 5, 2021

--

Photo by Dim Hou on Unsplash

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)

  1. 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
  2. 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

  1. 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🐱‍👤

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response