Sitemap
kc_dev

kc_dev

A developer with a passion for building dynamic apps. Enjoys working with modern frontend technologies to create intuitive user experiences and optimize code.

Array JS interview question map vs forEach

2 min readNov 16, 2024

--

In javascript two most commonly used methods for iteration on array are map and forEach

One liner answer:

map returns a new array with transformed elements, while forEach executes a function on each element without returning anything.

They have distinct use cases and behaviours.
In this article, we’ll explore their differences with examples to clarify when to use one over the other.

When to use map

Get kc_dev’s stories in your inbox

Join Medium for free to get updates from this writer.

Use map when you want to transform an array and create a new one. This is ideal for scenarios where you're generating a new array based on existing data.

const numbers = [1, 2, 3, 4]; // Using map to square each number 
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16]

When to use forEach

Use forEach when you need to perform an operation on each element of an array but do not need to create or return a new array.

const numbers = [1, 2, 3, 4]; // Using forEach to log each number
numbers.forEach(num => console.log(num));

// Output:
// 1
// 2
// 3
// 4

Conclusion

Understanding the difference between map and forEach is essential for writing efficient and clean JavaScript code. If your goal is to create a new array with modified elements, use map. For side effects like logging or updating variables, forEach is a better fit.

By knowing when to use each, you can write code that’s not only functional but also optimised for performance and clarity.

--

--

kc_dev
kc_dev

Written by kc_dev

A developer with a passion for building dynamic apps. Enjoys working with modern frontend technologies to create intuitive user experiences and optimize code.