Array iteration methods operate on every item in an array. Instead of using traditional
for loops, these methods provide a more readable and functional way to
process data collections.
The forEach() method calls a function (callback) once for each array element.
const numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value, index, array) {
console.log(value);
}
The map() method creates a new array by performing a function
on each array element. It does not change the original array.
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(x => x * 2);
// Result: [90, 8, 18, 32, 50]
The filter() method creates a new array with array elements
that pass a "test".
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(value => value > 18);
// Result: [45, 25]
The reduce() method runs a function on each array element to produce (reduce it
to) a single value. A common use is finding the sum of all numbers.
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce((total, value) => total + value);
// Result: 99
every(): Checks if all array values pass a test.some(): Checks if some array values pass a test.const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(x => x > 18); // false
let someOver18 = numbers.some(x => x > 18); // true
for loopsmap() and filter() return new arraysforEach() does not return anything (used for side
effects)reduce() turns an array into a single result (sum, average, object, etc.)