Middle
What is the difference between the array methods filter and forEach?
sobes.tech AI
Answer from AI
The array method filter creates and returns a new array containing only those elements of the original array for which the predicate function returns true. It does not modify the original array.
The forEach method simply executes a specified function for each element of the array, without returning a new array and without modifying the original array (unless the function explicitly changes the elements).
Example:
const arr = [1, 2, 3, 4];
const filtered = arr.filter(x => x % 2 === 0); // [2, 4]
arr.forEach(x => console.log(x)); // Will output 1, 2, 3, 4 in sequence
Thus, filter is used to create a new filtered array, while forEach is used to perform side effects with the elements without creating a new array.