Junior
When are the methods array.forEach and array.map used?
sobes.tech AI
Answer from AI
forEach is used to iterate over array elements and perform an action for each element. It does not create a new array and does not return a value. Suitable for performing side effects (e.g., logging, DOM manipulation).
map is used to transform each element of an array and create a new array from the transformation results. It always returns a new array of the same length. Suitable for obtaining a new set of data based on an existing one.
Example:
const numbers = [1, 2, 3];
// Using forEach to output each element
numbers.forEach((number) => {
console.log(number); // 1, 2, 3
});
// Using map to create an array of squares of numbers
const squares = numbers.map((number) => {
return number * number;
});
console.log(squares); // [1, 4, 9]
Comparison table:
| Feature | forEach |
map |
|---|---|---|
| Return value | undefined |
New array |
| Purpose | Perform actions for each element | Transform elements, create a new array |
| Modifies original array | No (unless the element itself is changed) | No |