DEV Community

Manikanta
Manikanta

Posted on

1 3

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs