Array Iteration Methods
JavaScript provides a suite of built-in array methods for iterating over elements. These methods encourage a functional programming style and make data transformation declarative and highly readable.
1. forEach
Executes a provided function once for each array element. It is used for side effects (like logging or mutating external variables) and returns undefined.
const users = ['Alice', 'Bob', 'Charlie'];
users.forEach((user, index) => {
console.log(`${index}: ${user}`);
});
2. Transformation: map
Creates a new array populated with the results of calling a provided function on every element. It does not mutate the original array.
const prices = [10, 20, 30];
const withTax = prices.map(price => price * 1.2);
// [12, 24, 36]
3. Filtering: filter
Creates a new array with all elements that pass the test implemented by the provided function.
const ages = [12, 17, 22, 30, 15];
const adults = ages.filter(age => age >= 18);
// [22, 30]
4. Accumulation: reduce and reduceRight
reduce executes a "reducer" callback function on each element, passing in the return value from the calculation on the preceding element. It resolves the array to a single value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); // 0 is the initial value
// sum is 10
reduceRight works exactly the same but processes the array from right-to-left.
5. Searching: find and findIndex
find: Returns the value of the first element that satisfies the testing function. Returnsundefinedif none is found.findIndex: Returns the index of the first element that satisfies the testing function. Returns-1if none is found.
const inventory = [
{ name: 'apples', quantity: 2 },
{ name: 'bananas', quantity: 0 },
{ name: 'cherries', quantity: 5 }
];
const available = inventory.find(item => item.quantity > 0);
// { name: 'apples', quantity: 2 }
const emptyIndex = inventory.findIndex(item => item.quantity === 0);
// 1
6. Boolean Testing: some and every
These methods return a boolean value based on conditions.
some: Returnstrueif at least one element passes the test.every: Returnstrueif all elements pass the test.
const scores = [45, 80, 92, 65];
const hasFailed = scores.some(score => score < 50);
// true
const allPassed = scores.every(score => score >= 50);
// false
Summary of Iteration Methods
- Need to return a new array? Use
map. - Need a subset of the array? Use
filter. - Need a single accumulated value? Use
reduce. - Need to check if a condition is met? Use
someorevery. - Need to find a specific item? Use
find. - Just doing a loop for side effects? Use
forEach.