What is the difference between Array.forEach() and Array.map()?
Asked on Jul 30, 2024
Answer
Array.forEach() and Array.map() are both methods used to iterate over arrays in JavaScript, but they serve different purposes. Array.forEach() is used for executing a function on each array element without returning a new array, while Array.map() creates a new array with the results of calling a provided function on every element.
// Example using Array.forEach()
const numbers = [1, 2, 3];
numbers.forEach((number) => {
console.log(number * 2); // Logs 2, 4, 6
});
// Example using Array.map()
const doubled = numbers.map((number) => number * 2);
console.log(doubled); // Logs [2, 4, 6]
Additional Comment:
✅ Answered with JavaScript best practices.- Array.forEach() executes a provided function once for each array element but does not return a new array.
- Array.map() applies a function to each element and returns a new array with the transformed values.
- Use Array.forEach() when you need to perform side effects like logging or modifying external variables.
- Use Array.map() when you need to transform data and create a new array based on the transformation.
Recommended Links:
← Back to All Questions