loading...

When should I use forEach and map of JavaScript Array?

immnk profile image Manikanta ・1 min read

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` };
      });

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.

That's all folks.

Posted on Jan 9 by:

immnk profile

Manikanta

@immnk

Mobile and Front End Developer | UI UX | Web Designer | Foodie | Tech Enthusiastic | Developer #DBS | Proud Indian

Discussion

markdown guide