DEV Community

Muhammad Salman
Muhammad Salman

Posted on

Leveraging Array Methods the Right Way in JavaScript

In JavaScript, methods like map, filter, concat, and reduce are "pure" – meaning they don't change the original array. Instead, they produce a new array based on the logic you supply.

For instance, when you do:

xs.map(x => x.prop);
Enter fullscreen mode Exit fullscreen mode

The original array xs remains untouched, and a brand new array is returned with the mapped values.

But here's a pitfall: some folks might be tempted to use a map just to loop over the array, say for logging:

xs.map((x, i) => console.log(`element #${i}:`, x));
Enter fullscreen mode Exit fullscreen mode

This misuses map, which is intended to transform data, not just to iterate. For side effects like logging, forEach is a much better choice:

xs.forEach((x, i) => console.log(`element #${i}:`, x));
Enter fullscreen mode Exit fullscreen mode

Bad Practice:

Using map without utilizing its return value:

characters.map(character => character.name);
console.log(characters); // The original array remains unchanged!
Enter fullscreen mode Exit fullscreen mode

Recommended:

Use map when you actually intend to create a new transformed array:

const characterNames = characters.map(character => character.name);
console.log(characterNames); // A shiny new array with character names!
Enter fullscreen mode Exit fullscreen mode

The lesson? Make sure to use array methods in a way that aligns with their intended purpose. This ensures that your code is both efficient and easy for others to understand.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay