map vs forEach
map and forEach are both methods in JavaScript used to iterate over arrays, but they serve different purposes and have different behaviors:
map Method:
Purpose: The map method is used to transform an array by applying a function to each element of the array, creating a new array with the results.
Return Value: It returns a new array containing the results of applying the provided function to each element of the original array.
Example:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num * num);
// squaredNumbers is [1, 4, 9, 16, 25]
Note: map does not modify the original array; it creates a new one.
forEach Method:
Purpose: The forEach method is used for iterating over the elements of an array and performing some action for each element. It is typically used when you want to execute a function for its side effects, such as printing or updating variables.
Return Value: forEach returns undefined. It doesn't create a new array or return any values.
Example:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num) => console.log(num));
// Prints each number to the console
Note: forEach is often used when you want to iterate over an array purely for its side effects because it doesn't produce a new array or modify the original array.
In summary, the main difference between map and forEach is their purpose and return value:
Use map when you want to transform an array into a new array based on a transformation function.
Use forEach when you want to iterate over the elements of an array and perform some action for each element, often for its side effects.