Junior — Middle
What exactly does the forEach method return when iterating over a collection?
sobes.tech AI
Answer from AI
The forEach method in JavaScript (and in many other languages) does not return any value — its return value is undefined. It is designed to execute a function for each element of a collection, but not to create a new array or collect results.
For example:
const arr = [1, 2, 3];
const result = arr.forEach(item => console.log(item));
console.log(result); // undefined
If you need to get a new array with results, you should use the map, filter, or reduce methods.
Thus, forEach is used for side effects (e.g., logging to the console, modifying external variables), not for data transformation.