Array Methods (map/filter/reduce)Intermediate
1Question 1 of 1
javascriptHow do map, filter, and reduce work in JavaScript and why are they considered immutable?
Explanation & Concept
Array transformations using `map`, `filter`, and `reduce` are functional programming primitives that process arrays without mutating the original source array:
• `map(fn)`: Transforms every element and returns a new array of identical length. • `filter(fn)`: Tests each element against a predicate and returns a new array containing only matching elements. • `reduce(fn, initial)`: Combines array elements into a single accumulated result (e.g. sum, object, or grouped array).
Code Example
javascript
const transactions = [
{ id: 1, type: "income", amount: 2000 },
{ id: 2, type: "expense", amount: 150 },
{ id: 3, type: "income", amount: 450 },
{ id: 4, type: "expense", amount: 50 }
];
// Chain filter, map, and reduce immutably
const totalIncome = transactions
.filter((tx) => tx.type === "income")
.map((tx) => tx.amount)
.reduce((sum, amount) => sum + amount, 0);
console.log("Total Income:", totalIncome); // 2450
console.log("Original untouched:", transactions.length); // 4How It Works & Key Takeaways
Because none of these methods mutate the original `transactions` array, state predictability is preserved, eliminating unexpected side-effects.
Mock Test · 1 Questions · Optional
Ready for Destructuring & Spread/Rest?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions