1. What does the forEach method return?
The forEach method always returns undefined. It does not return a new array. ForEach is used for its side effects, like logging or updating DOM elements, not for transforming arrays. It executes a callback function for each element but does not create or return anything. If you need to transform an array, use map instead. You cannot break or continue out of forEach. Use a regular for loop if you need early exit.
const numbers = [1, 2, 3];
// forEach returns undefined
const result = numbers.forEach(num => num * 2);
console.log(result); // undefined
// Used for side effects
numbers.forEach(num => {
console.log(num); // Just logging
});
// Accessing index and array
fruits.forEach((fruit, index, array) => {
console.log(index, fruit, array.length);
});
// Compare with map (returns new array)
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
// Cannot break out of forEach
numbers.forEach(num => {
// if (num === 2) break; // SyntaxError!
console.log(num);
});
// Use for...of if you need break
for (const num of numbers) {
if (num === 2) break; // Works!
console.log(num);
}