Loops work, but modern JavaScript has a neater way to handle lists: array methods that take a function and apply it to each item for you. Want every price with tax added? Use map. Only the cheap items? Use filter. The total? Use reduce. Your code becomes shorter and easier to read.
Each array method answers one specific question about a list, and its name tells the reader which question that is. A filter call clearly keeps some items and drops others, whereas a for loop could be doing anything until you read every line. That clarity is why array methods are used so heavily in modern code.
map, filter and reduce
| Method | Question it answers | Returns |
|---|---|---|
map(fn) | "What does each item become?" | A new array of the same length |
filter(fn) | "Which items should I keep?" | A new array, possibly shorter |
reduce(fn, start) | "What single value do they combine into?" | One value |
None of these change the original array. They return something new, so store the result in a variable.
reduce is the hardest of the three at first. Think of it as carrying a running total: (sum, n) => sum + n takes the total so far and the next item, and returns the new total. The second argument, often 0, is the starting value.
Searching and checking with find, some and every
| Method | Returns |
|---|---|
find(fn) | The first item for which fn returns true, or undefined |
findIndex(fn) | That item's index, or -1 |
some(fn) | true if at least one item passes |
every(fn) | true if all items pass |
includes(x) | true if that exact value is in the array |
Use find when you need the item itself, such as the product with a particular id, and some or every when you only need a yes or no answer.
Looping and sorting
forEach(fn)runs code for each item and returns nothing. Use it for side effects, such as logging or updating the page.sort(compareFn)sorts the array in place, changing the original. Numbers need a compare function:(a, b) => a - bsorts from low to high and(a, b) => b - afrom high to low.toSorted()works likesortbut returns a sorted copy and leaves the original alone.flat()flattens nested arrays into a single level.
Without a compare function, sort compares items as text, which is why [10, 9, 1].sort() gives [1, 10, 9].
The callback's arguments
Each method calls your function with three arguments: (item, index, array). Most of the time you only need item, but index is useful for numbering, as in items.map((item, i) => ${i + 1}. ${item}).
JavaScript Array Methods Syntax
Array method shapes
arr.map(item => newValue);
arr.filter(item => trueOrFalse);
arr.find(item => trueOrFalse);
arr.reduce((acc, item) => newAcc, startValue);
arr.forEach(item => { /* do something */ });
arr.toSorted((a, b) => a - b);JavaScript Array Methods Summary
- Array methods take a function and apply it to every item.
maptransforms,filterselects andreducecombines into one value.find,someandeverysearch and check items.sortchanges the original array;toSortedreturns a copy.- Chain methods to process data step by step.
JavaScript Array Methods Examples
Each example runs in the page. Edit the code and press Run to see what changes.
map and filter
const temps = [12, 25, 31, 8, 19];
const fahrenheit = temps.map(c => c * 9 / 5 + 32);
const warmDays = temps.filter(c => c >= 20);
const labels = temps.map((c, i) => `Day ${i + 1}: ${c}°C`);
console.log(fahrenheit);
console.log(warmDays);
console.log(labels);
console.log(temps);Line-by-line explanation
- Line 3Every temperature is converted, and there are still 5 items.
- Line 4Keep only temperatures of 20 or more.
- Line 5The second argument is the index.
- Line 10The original array is unchanged.
Working with arrays of objects
Real data usually looks like this.
const products = [
{ name: "Notebook", price: 4, inStock: true },
{ name: "Backpack", price: 35, inStock: false },
{ name: "Pen set", price: 9, inStock: true },
{ name: "Lamp", price: 22, inStock: true },
];
const names = products.map(p => p.name);
const available = products.filter(p => p.inStock);
const lamp = products.find(p => p.name === "Lamp");
const anyCheap = products.some(p => p.price < 5);
const allInStock = products.every(p => p.inStock);
const total = available.reduce((sum, p) => sum + p.price, 0);
console.log(names);
console.log(available.length, "available");
console.log(lamp);
console.log(anyCheap, allInStock);
console.log("Total of available:", total);Line-by-line explanation
- Line 8Pull out one property from every object.
- Line 9Keep the ones in stock.
- Line 10The first object whose name is "Lamp".
- Lines 11 to 12Is any item under £5? Are all in stock?
- Line 13Add up prices: start at 0, add each price to the running
sum.
Sorting and chaining
const scores = [
{ player: "Ava", points: 82 },
{ player: "Ben", points: 95 },
{ player: "Cy", points: 67 },
];
const leaderboard = scores.toSorted((a, b) => b.points - a.points);
leaderboard.forEach((s, i) => {
console.log(`${i + 1}. ${s.player}: ${s.points}`);
});
const average = scores
.map(s => s.points)
.reduce((sum, p) => sum + p, 0) / scores.length;
console.log("Average:", average.toFixed(1));
console.log([10, 9, 1].sort());Line-by-line explanation
- Line 7Sorted copy, highest points first.
- Lines 9 to 11
forEachto print each row. - Lines 13 to 15Chain: get the points, add them up, divide.
- Line 18Careful! Without a compare function,
sortcompares as strings: [1, 10, 9].
Common JavaScript Array Methods Mistakes
Forgetting to return in a callback
const doubled = [1, 2, 3].map(n => { n * 2 }); // [undefined, undefined, undefined]const doubled = [1, 2, 3].map(n => n * 2);Using forEach when you want a new array
const names = users.forEach(u => u.name); // undefinedconst names = users.map(u => u.name);forEach always returns undefined.
Sorting numbers without a compare function
[40, 100, 5].sort(); // [100, 40, 5][40, 100, 5].sort((a, b) => a - b); // [5, 40, 100]JavaScript Array Methods in Real Projects
Data in, interface out
Most front-end work is exactly this: an API gives you an array of objects, you filter by what the user searched, toSorted by price, map each one into HTML, and reduce to show a total. React apps render lists with items.map(…) constantly.
JavaScript Array Methods Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Double every number, then keep only those over 5.
const result = [1, 2, 3, 4]
.(n => n * 2)
.(n => n > 5);
console.log(result); // [6, 8]
map transforms each item; filter keeps items that pass the test.What does this print?
const r = [3, 5, 7].reduce((sum, n) => sum + n, 10);
console.log(r);Which method returns the first matching item (not an array)?
find returns a single item; filter returns an array.What does this print?
const ages = [12, 19, 25];
console.log(ages.some(a => a < 13), ages.every(a => a > 18));The code should log the names of users over 18 in alphabetical order: ["Ana", "Zoe"]. Fix it.
const users = [
{ name: "Zoe", age: 22 },
{ name: "Max", age: 16 },
{ name: "Ana", age: 30 },
];
const adults = users.forEach(u => u.age > 18);
const names = adults.map(u => { u.name });
console.log(names.sort());- Logs ["Ana", "Zoe"]
- No errors
JavaScript Array Methods Quiz
4 questions to check what you learned.
Does
mapchange the original array?- Yes
- No, it returns a new array
- Only for numbers
- Only if you use const
What does
[1, 2, 3].filter(n => n > 5)return?- []
- undefined
- null
- false
What's the difference between
sort()andtoSorted()?- toSorted is alphabetical only
- There's no difference
- sort is newer
- sort changes the original array; toSorted returns a sorted copy
In
reduce((acc, n) => acc + n, 0), what isacc?- The current index
- The original array
- The running result (accumulator) from the previous step
- Always 0
JavaScript Array Methods Challenge
Order summary
Using array methods (no loops):
itemNames: an array of names, usingmapveggie: only items wherevegetarianis true, usingfilterbill: the total ofprice * qtyfor all items, usingreduce- Log
Bill: 31.5
const order = [
{ name: "Margherita", price: 9, qty: 2, vegetarian: true },
{ name: "Pepperoni", price: 10.5, qty: 1, vegetarian: false },
{ name: "Garlic bread", price: 3, qty: 1, vegetarian: true },
];
- itemNames is correct
- veggie has the 2 vegetarian items
- bill is 31.5
- Logs "Bill: 31.5"
- Uses map, filter and reduce