DEV Community

Manikanta
Manikanta

Posted on

When should I use forEach and map of JavaScript Array?

I have always contemplated over when to use forEach and map of Javascript array. Both forEach and map does the same thing of running a function over every element of the array. But when should I use each one of these functions?

Scenario 1:
I want to create a new array based on a function. A transformation.

const tenants = [
      { env: 'prod', users: 10 },
      { env: 'pre-prod', users: 5 },
      { env: 'dev', users: 1000 },
      undefined
    ];
const modifiedTenants = 
      .filter(Boolean)
      .sort((a, b) => a.env.localeCompare(b.env))
      .map((tenant) => {
        return { ...tenant, message: `${tenant.env} has ${tenant.users} users` };
      });

Enter fullscreen mode Exit fullscreen mode

Scenario 2:
I want to read a set of files synchronously from a file server and do some awesome stuff while I do not need to modify my array nor care about the results of this because I do awesome stuff immediately.

const jsFiles = [];
jsFiles.forEach(async (file) => {
   const fileContent = await fs.readFile(file, 'UTF-8');
   this.doAwesomeStuff(fileContent);
});
// Do see that I don't assign the results of forEach to anything because it doesn't return anything useful.
Enter fullscreen mode Exit fullscreen mode

That's all folks.

Top comments (0)