Definition:
- Creates a new array by transforming each element of the original array through a callback function.
- Does not mutate the original array
- Always returns an array of the same length
Syntax:
array.map(callback(currentValue, index, array), thisArg);Example:
const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]💡 When to use: When you want to transform every element.
Definition:
- Creates a new array containing only the elements that pass a condition (callback returns true).
- Does not mutate the original array
- New array can be shorter (or even empty)
Syntax:
array.filter(callback(currentValue, index, array), thisArg);Example:
const numbers = [1, 2, 3, 4];
const evens = numbers.filter((num) => num % 2 === 0);
console.log(evens); // [2, 4]💡 When to use: When you want to keep only the items that match a condition.
Definition:
- Executes a reducer callback on each array element, accumulating the result into a single value.
- Can be used for sum, product, max, min, or even building objects
- Accepts an initial value for the accumulator
Syntax:
array.reduce(callback(accumulator, currentValue, index, array), initialValue);Example:
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10💡 When to use: When you want to combine all elements into a single result.
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 25 },
];
const namesOfAdults = people
.filter((person) => person.age >= 18) // keep only adults
.map((person) => person.name) // extract names
.reduce((acc, name) => acc + ', ' + name); // join into string
console.log(namesOfAdults); // "Alice, Charlie"This is a real-world FP chain: filter → map → reduce.
- Immutability: None of these methods mutate the original array.
- Functional Programming: They encourage declarative code instead of manual loops.
- Performance: Each creates a new array (except reduce), so chaining can create intermediate arrays — in large datasets, consider combining logic in a single reduce for performance.
- Alternatives: You could implement these manually with for loops, but these methods improve readability and expressiveness.