JavaScript Array Iteration Methods
JavaScript provides powerful iteration methods that let you loop through arrays, transform data, filter elements, and reduce arrays to single values. These methods are the backbone of functional programming in JavaScript.
forEach()
forEach() executes a provided function once for each array element. It does not return a new array and cannot be chained. Use it for side effects like logging.
const fruits = ["Apple", "Banana", "Cherry"];
// Basic forEach
fruits.forEach(function(item, index) {
console.log(`${index}: ${item}`);
});
// Arrow function
fruits.forEach((item, index, array) => {
console.log(`${item} is at position ${index} of ${array.length}`);
});map()
map() creates a new array by calling a function on every element. It returns a new array of the same length with transformed values. The original array is not modified.
const numbers = [1, 2, 3, 4, 5];
// Double each number
const doubled = numbers.map(n => n * 2);
console.log("Doubled:", doubled);
// Extract property from objects
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];
const names = users.map(u => u.name);
console.log("Names:", names);
// Transform with index
const indexed = numbers.map((n, i) => `Item ${i}: ${n}`);
console.log("Indexed:", indexed);filter()
filter() creates a new array with all elements that pass a test. The callback function should return true to keep the element or false to exclude it.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Even numbers
const evens = numbers.filter(n => n % 2 === 0);
console.log("Evens:", evens);
// Filter objects
const products = [
{ name: "Laptop", price: 999 },
{ name: "Phone", price: 699 },
{ name: "Tablet", price: 499 },
{ name: "Watch", price: 299 }
];
const expensive = products.filter(p => p.price > 500);
console.log("Expensive:", expensive.map(p => p.name));
// Remove falsy values
const mixed = [0, "hello", "", null, 42, undefined, "world"];
const truthy = mixed.filter(Boolean);
console.log("Truthy:", truthy);reduce()
reduce() executes a reducer function on each element, passing the result from one call to the next, reducing the array to a single value. It takes a callback and an optional initial value.
const numbers = [1, 2, 3, 4, 5];
// Sum all numbers
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log("Sum:", sum);
// Find maximum
const max = numbers.reduce((a, b) => a > b ? a : b);
console.log("Max:", max);
// Count occurrences
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const counts = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log("Counts:", counts);
// Flatten array
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
console.log("Flattened:", flat);every() and some()
every() returns true if ALL elements pass the test. some() returns true if ANY element passes the test. Both short-circuit: every() stops at the first false, some() stops at the first true.
const numbers = [2, 4, 6, 8, 10];
// every - all elements pass the test?
console.log("All even:", numbers.every(n => n % 2 === 0));
console.log("All > 5:", numbers.every(n => n > 5));
// some - at least one passes?
console.log("Some > 5:", numbers.some(n => n > 5));
console.log("Some > 20:", numbers.some(n => n > 20));
// Practical: validate form fields
const fields = [
{ name: "email", value: "a@b.com" },
{ name: "name", value: "" },
{ name: "age", value: "25" }
];
const allFilled = fields.every(f => f.value.length > 0);
console.log("All filled:", allFilled);
const hasEmpty = fields.some(f => f.value.length === 0);
console.log("Has empty:", hasEmpty);Chaining Methods
Since map(), filter(), and other methods return arrays, you can chain them together to create powerful data transformations in a readable way.
const products = [
{ name: "Laptop", price: 999, inStock: true },
{ name: "Phone", price: 699, inStock: false },
{ name: "Tablet", price: 499, inStock: true },
{ name: "Watch", price: 299, inStock: true },
{ name: "Camera", price: 899, inStock: true }
];
// Filter, transform, and reduce in one chain
const totalInStock = products
.filter(p => p.inStock)
.map(p => p.price)
.reduce((sum, price) => sum + price, 0);
console.log("Total in-stock value:", totalInStock);
// Get sorted names of affordable items
const affordable = products
.filter(p => p.price < 700 && p.inStock)
.map(p => p.name)
.sort();
console.log("Affordable & in stock:", affordable);| Method | Returns | Purpose |
|---|---|---|
| forEach() | undefined | Execute side effects |
| map() | New array | Transform each element |
| filter() | New array | Keep elements that pass test |
| reduce() | Single value | Accumulate into one value |
| every() | Boolean | Test if ALL pass |
| some() | Boolean | Test if ANY passes |