JavaScript Array Methods
Array methods transform and query arrays without manual loops.
Map
Creates a new array by transforming each element:
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map((n) => n * 2);
// [2, 4, 6, 8, 10]
Filter
Creates a new array with elements that pass a test:
let numbers = [1, 2, 3, 4, 5];
let evens = numbers.filter((n) => n % 2 === 0);
// [2, 4]
Reduce
Reduces an array to a single value:
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((acc, curr) => acc + curr, 0);
// 15
Remember: Always provide an initial value to reduce to avoid errors with empty arrays.
forEach
Executes a function for each element (no return value):
let numbers = [1, 2, 3];
numbers.forEach((n, i) => console.log(`Index ${i}: ${n}`));
Tip: Use forEach for side effects, map for transformations.
Find and FindIndex
let users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
let user = users.find((u) => u.id === 2); // { id: 2, name: "Bob" }
let index = users.findIndex((u) => u.id === 2); // 1
some and every
let numbers = [1, 2, 3, 4, 5];
numbers.some((n) => n % 2 === 0); // true (at least one)
numbers.every((n) => n > 0); // true (all)
Complete Example: Data Pipeline
let products = [
{ name: "Laptop", price: 999, inStock: true },
{ name: "Phone", price: 699, inStock: false },
{ name: "Tablet", price: 499, inStock: true }
];
let names = products.filter((p) => p.inStock).map((p) => p.name);
let total = products.filter((p) => p.inStock).reduce((s, p) => s + p.price, 0);
console.log(names); // ["Laptop", "Tablet"]
console.log(total); // 1498
Best Practices
- Use
mapfor transformations — not for side effects - Use
filterfor selection — not manualifin loops - Always provide initial value to
reduce— avoids errors - Use
findoverfilter[0]— more efficient
Common Mistakes
- Forgetting
returninmap/filter— arrow functions with{}need explicitreturn - Mutating original array — these methods return new arrays
- Missing initial value in
reduce— causes errors on empty arrays - Using
forEachto return values — it always returnsundefined