JavaScript provides powerful functional iteration methods (forEach, map, filter, reduce, some, every) that eliminate traditional for loops in favor of clean declarative data transformations.
flowchart TD
Iter["Array Higher-Order Methods"] --> Map["map(): Transform every element -> New Array"]
Iter --> Filter["filter(): Keep matching elements -> New Filtered Array"]
Iter --> Reduce["reduce(): Aggregate array -> Single Accumulated Value"]
Iter --> Each["forEach(): Execute side-effects -> Returns undefined"]
Iter --> Quant["some() / every(): Boolean quantification checks"]
| Method | Returns | Purpose | Callbacks Can Break/Stop Early? |
|---|---|---|---|
map(fn) |
New Array | Transforms each item into a new value. | No |
filter(fn) |
New Array | Retains items where callback returns true. |
No |
reduce(fn, init) |
Accumulated Value | Accumulates array into a single result (Object/Number). | No |
forEach(fn) |
undefined |
Executes side effects (logging, DOM updates). | No |
some(fn) |
boolean |
Checks if at least one item matches condition. | Yes (Short-circuits) |
every(fn) |
boolean |
Checks if all items match condition. | Yes (Short-circuits) |
// Demonstrating functional array iteration techniques
const cart = [
{ id: 1, name: "Keyboard", price: 80, quantity: 1, category: "Tech" },
{ id: 2, name: "Mouse", price: 40, quantity: 2, category: "Tech" },
{ id: 3, name: "Notebook", price: 10, quantity: 5, category: "Stationery" }
];
// 1. filter(): Get Tech items only
const techItems = cart.filter((item) => item.category === "Tech");
console.log("Tech Items:", techItems);
// 2. map(): Extract item names
const itemNames = cart.map((item) => item.name);
console.log("Item Names:", itemNames);
// 3. reduce(): Calculate Total Cart Value
const totalCartValue = cart.reduce((total, item) => {
return total + (item.price * item.quantity);
}, 0); // Initial accumulator seed = 0
console.log(`Total Cart Value: \$${totalCartValue}`); // $210
// 4. Quantifier checks: some() and every()
const hasExpensiveItem = cart.some((item) => item.price > 50);
const allItemsInStock = cart.every((item) => item.quantity > 0);
console.log(`Has item > \$50: ${hasExpensiveItem}`); // true
console.log(`All items in stock: ${allItemsInStock}`); // true
map() for Side Effects: If you do not intend to use the returned transformed array, use forEach() or for...of instead of map().reduce(): Always pass an initial accumulator value as the second parameter to reduce() to prevent errors on empty arrays.break Out of forEach(): You cannot use break or continue inside forEach(). Use a standard for...of loop if early loop termination is needed.Use reduce() to transform an array of category strings ["Tech", "Tech", "Stationery"] into an object counting occurrences ({ Tech: 2, Stationery: 1 }).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.