Array Methods: map, filter, forEach, reduce
Beyond push and pop, arrays have powerful methods for transforming and processing their data, without you writing a manual loop yourself. .forEach() runs a function once for every item, mainly for side effects like logging: fruits.forEach(f => console.log(f));. It doesn't return a new array. .map() creates a brand-new array by transforming every item: const upper = fruits.map(f => f.toUpperCase());. The original array is untouched; upper is a new array with the transformed values. .filter() creates a new array containing only the items that pass a test: const longNames = fruits.filter(f => f.length > 5);. Each item is kept only if the function returns true for it. .reduce() combines every item into a single value, like a total: const total = [1, 2, 3].reduce((sum, n) => sum + n, 0); calculates 6. The 0 is the starting value for sum, and each step adds the next number to it. These four methods are used constantly in real JavaScript learning them well pays off for the rest of your coding life.
Why this matters
- ·map, filter, and reduce replace many manual loops with shorter, more readable code.
- ·These methods don't modify the original array, which avoids a whole category of accidental bugs.
- ·They're standard, widely-used patterns recognizable to any experienced JavaScript developer.
Common mistakes
- ·Forgetting that map and filter return a new array (rather than changing the original) can lead to confusion about which array holds what.
- ·Using forEach when you actually need the transformed result (like map) means you'll get undefined instead of useful data.
- ·reduce is the most powerful but also the easiest to get wrong always double-check its starting value and what it returns each step.
Frequently asked questions
No. It returns a brand-new array with the transformed values; the original stays exactly as it was.
Practice questions
Question 1
Use .map() to create an array where each number in [1,2,3] is squared.
Question 2
Use .filter() to keep only numbers greater than 10 from an array of your choice.
Quick check
Just for this topic answer honestly, then check yourself.
1 / 3
