Array iteration methods operate on every element of an array, making it easy to loop through arrays and perform actions without writing a manual for loop. These methods are a cornerstone of modern, functional JavaScript.
forEach() MethodThe forEach() method calls a function (a callback function) once for each array element. It is a simple and readable way to iterate over an array.
const fruits = ["apple", "orange", "cherry"];fruits.forEach(myFunction);
function myFunction(item, index, arr) { console.log("Item at index " + index + " is " + item); }
Note: The callback function can accept three arguments: the item value, the item index, and the array itself.
map() MethodThe map() method creates a new array by performing a function on each element of the original array. It does not change the original array.
const numbers1 = [4, 9, 16, 25];// Create a new array with the square root of each number const numbers2 = numbers1.map(Math.sqrt);
console.log(numbers2); // [2, 3, 4, 5]
filter() MethodThe filter() method creates a new array with all elements that pass a test (provided as a function).
const ages = [32, 33, 16, 40];// Create a new array with only the adults const adults = ages.filter(checkAdult);
function checkAdult(age) { return age >= 18; }
console.log(adults); // [32, 33, 40]
reduce() MethodThe reduce() method runs a function on each array element to produce (or reduce it to) a single value. It works from left-to-right in the array.
const numbers = [1, 2, 3, 4];// Get the sum of all numbers const sum = numbers.reduce(myFunction);
function myFunction(total, value) { return total + value; }
console.log(sum); // 10
every() and some()every(): Checks if all elements in an array pass a test. Returns true or false.some(): Checks if at least one element in an array passes a test. Returns true or false.const numbers = [4, 9, 16, 25, 29];let allOver18 = numbers.every(value => value > 18); let someOver18 = numbers.some(value => value > 18);
console.log(allOver18); // false console.log(someOver18); // true
Which method creates a new array by transforming every element in an existing array?