Arrays and the Functional Pipeline: map, filter, and reduce
In real-world web applications, data almost always arrives in lists:
- A list of products on an e-commerce page
- A list of chat messages from friends
- A list of search results
- A list of stock prices over time
In JavaScript, we organize lists using Arrays.
By the end of this lesson, you will master:
- How JavaScript arrays store and index items
- Adding and removing items (
push,pop,shift,unshift) - Why modern web developers prefer declarative methods over old-fashioned
forloops - The Holy Trinity of JavaScript Array Methods:
map(),filter(), andreduce()
1. What Is an Array in JavaScript?
An array is an ordered collection of values enclosed in square brackets [ ... ]:
const fruits = ["Apple", "Banana", "Cherry"];const scores = [95, 82, 99, 100];Zero-Based Indexing:
Just like in Python and Java, JavaScript counts positions starting at zero:
Index: 0 1 2
┌──────────┬──────────┬──────────┐
fruits = │ Apple │ Banana │ Cherry │
└──────────┴──────────┴──────────┘
You can access or update items using their index:
console.log(fruits[0]); // "Apple"console.log(fruits[1]); // "Banana"// You can check the length:console.log(fruits.length); // 32. Common Array Mutation Methods
JavaScript arrays include built-in methods to modify their contents:
const cart = ["Shirt", "Shoes"];// 1. push(): Adds to the ENDcart.push("Hat"); // ["Shirt", "Shoes", "Hat"]// 2. pop(): Removes from the ENDcart.pop(); // Returns "Hat", cart is now ["Shirt", "Shoes"]// 3. unshift(): Adds to the BEGINNINGcart.unshift("Socks"); // ["Socks", "Shirt", "Shoes"]// 4. shift(): Removes from the BEGINNINGcart.shift(); // Returns "Socks", cart is now ["Shirt", "Shoes"]3. The Modern Functional Paradigm 🚀
In traditional programming, if you wanted to double every number in an array, you would write a manual for loop:
// The Old Imperative Way (Tedious & Error-Prone):const numbers = [1, 2, 3, 4];const doubled = [];for (let i = 0; i < numbers.length; i++) { doubled.push(numbers[i] * 2);}In modern JavaScript (and modern frameworks like React), developers use declarative array transformation methods. They are cleaner, easier to read, and do not mutate the original array.
Let's meet the big three:
A. .map() — The 1-to-1 Transformer 🔄
Use .map() when you want to transform every single item in an array into something new.
It returns a brand new array with the exact same length:
const prices = [10, 20, 30];// Double every price:const doubledPrices = prices.map(price => price * 2);console.log(doubledPrices); // [20, 40, 60]console.log(prices); // [10, 20, 30] (Original is untouched!)B. .filter() — The Conditional Gatekeeper 🛡️
Use .filter() when you want to keep only items that satisfy a condition.
It calls your test function on each item:
- If the function returns
true, the item is included. - If the function returns
false, the item is excluded.
const scores = [45, 88, 92, 59, 74];// Keep only passing scores (>= 60):const passingScores = scores.filter(score => score >= 60);console.log(passingScores); // [88, 92, 74]C. .reduce() — The Aggregator / Accumulator 🧮
Use .reduce() when you want to boil an entire array down to a single value (e.g. sum of all numbers, total shopping cart cost, or finding the maximum).
It passes an accumulator (acc) and the current item (curr) through every iteration:
const expenses = [50, 120, 30, 200];// Sum all expenses starting with an initial accumulator of 0:const totalCost = expenses.reduce((acc, curr) => acc + curr, 0);console.log(totalCost); // 400Interactive Array Pipeline Simulator 🕹️
Step through .map(), .filter(), and .reduce() in the live pipeline simulator below. Watch elements pass through callback functions, inspect intermediate logs, and verify how the original array remains completely pure and unmodified:
Why Master map, filter, and reduce? In modern React, Vue, and Node.js, you almost never write old-fashioned for loops. Functional array methods produce clean, declarative code that never accidentally mutates your original state!
[!TIP] Key Takeaways
- Arrays use zero-based indexing (
arr[0]) and have a.lengthproperty..map(): Transforms every element → returns a new array of the same length..filter(): Evaluates a condition → returns a new array with a subset of items..reduce(): Combines all elements → returns a single accumulated value.- All three methods are pure functions that never mutate the original array!