📖 Notes LESSON 16 OF 32

Arrays — map, filter, reduce

⏱️ 26 min
JavaScript

Stop Writing For-Loops

map, filter, and reduce transform arrays without mutating the original — this is the backbone of how React renders lists and how you'll shape API data everywhere in this course.

The Big Four

🔄
.map()
Transforms every item, returns a new array of the same length.
🔍
.filter()
Keeps only items that pass a test, returns a new (possibly shorter) array.
.reduce()
Collapses an array into a single value (sum, object, count).
🎯
.find()
Returns the first item that matches, or undefined.

Spread Operator

The spread operator (...) copies array/object contents — used constantly to add items without mutating state, especially in React.

map / filter / reduce / find / spread
JS
const nums = [1, 2, 3, 4, 5];

const doubled = nums.map(n => n * 2);        // [2,4,6,8,10]
const evens   = nums.filter(n => n % 2 === 0); // [2,4]
const total   = nums.reduce((sum, n) => sum + n, 0); // 15
const first3  = nums.find(n => n > 3);       // 4

// Spread — copy + add without mutating
const withSix = [...nums, 6];
const merged  = { ...userA, ...userB };
Why immutability matters
None of these methods change the original array — they return new ones. React relies on this: it detects changes by comparing old and new references, so mutating an array directly (e.g. arr.push()) can make React miss the update entirely.
🗒 Cheat Sheet 📝 Worksheet