Introduction & Syntax
Array Methods · Study material
Modern JavaScript processes data with array methods instead of hand-written loops: map to transform, filter to select, reduce to summarise, find to search, some and every to check. They are used in every React component and Node.js service – and in almost every JavaScript interview, usually with a twist: reduce without an initial value, forEach returning undefined, ["1", "2", "3"].map(parseInt), or every on an empty array. This topic covers each method, how they combine and the traps around them. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
The core methods
| Method | Returns | Use it to |
|---|---|---|
forEach(fn) | undefined | run a side effect for each element |
map(fn) | new array, same length | transform every element |
filter(fn) | new array of the elements where fn is truthy | select elements |
reduce(fn, initial) | one value of any type | sum, count, group, build objects |
find(fn) / findLast(fn) | first / last matching element or undefined | look up one item |
findIndex(fn) / findLastIndex(fn) | index or -1 | locate one item |
some(fn) / every(fn) | boolean | "any?" / "all?" |
flat(depth) / flatMap(fn) | new flattened array | remove nesting |
None of these change the original array (unless the callback does). sort and reverse do – use toSorted / toReversed for copies.
const prices = [120, 450, 80, 999];
const withGst = prices.map((p) => Math.round(p * 1.18)); // transform every element → same length
const above100 = prices.filter((p) => p > 100); // keep elements where the callback is truthy
const total = prices.reduce((sum, p) => sum + p, 0); // combine everything into one value
console.log(withGst, above100, total);
console.log(prices); // none of them changed the original
[ 142, 531, 94, 1179 ] [ 120, 450, 999 ] 1649 [ 120, 450, 80, 999 ]
Callback arguments
Every callback receives (element, index, array). That is useful (the index is often needed) and dangerous when you pass a function that takes optional extra parameters: map(parseInt) passes the index as parseInt's radix. Pass a wrapper (s => parseInt(s, 10)) or a one-argument function such as Number.
// Callbacks receive (element, index, array)
console.log(["a", "b"].map((value, index, arr) => `${index}:${value}/${arr.length}`));
// So map(parseInt) calls parseInt("1", 0), parseInt("2", 1), parseInt("3", 2) – the index becomes the radix
console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map(Number)); // Number takes one argument: safe
[ '0:a/2', '1:b/2' ] [ 1, NaN, NaN ] [ 1, 2, 3 ]
Searching: find, findIndex, some and every
find returns the element itself (not an array) or undefined; findIndex returns -1 when nothing matches; findLast and findLastIndex search from the end. some stops at the first truthy result and every at the first falsy one. On an empty array, some is false and every is true ("all of nothing").
const users = [
{ id: 1, name: "Asha", active: true },
{ id: 2, name: "Ravi", active: false },
{ id: 3, name: "Meera", active: true },
];
console.log(users.find((u) => u.active).name, users.findLast((u) => u.active).name);
console.log(users.findIndex((u) => u.id === 2), users.find((u) => u.id === 9));
// some: at least one; every: all of them. An empty array: some → false, every → true
console.log(users.some((u) => !u.active), users.every((u) => u.name.length >= 4), [].every((x) => x > 100));
Asha Meera 1 undefined true true true
reduce in depth
arr.reduce((accumulator, element, index, array) => newAccumulator, initialValue). The callback must return the accumulator for the next step. With an initial value, the first call gets it and the first element; without one, the first element becomes the accumulator and processing starts at the second – and an empty array without an initial value throws a TypeError. Always pass an initial value unless you are certain the array is non-empty and of the right type. reduceRight works from the end.
const orders = [
{ city: "Pune", amt: 500 },
{ city: "Delhi", amt: 300 },
{ city: "Pune", amt: 200 },
];
// reduce into an object: totals per city
const byCity = orders.reduce((acc, o) => {
acc[o.city] = (acc[o.city] ?? 0) + o.amt;
return acc; // always return the accumulator
}, {});
// without an initial value, the first element is the starting accumulator
const max = [4, 9, 2].reduce((a, b) => Math.max(a, b));
console.log(byCity, max);
{ Pune: 700, Delhi: 300 } 9flat and flatMap
flat(depth = 1) removes that many levels of nesting (Infinity for all). flatMap(fn) maps and then flattens one level, so a callback can return an empty array to drop an element or several items to expand it.
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(), nested.flat(Infinity)); // default depth is 1
// flatMap = map, then flat by one level: one input can produce 0, 1 or many outputs
console.log(["hello world", "hi"].flatMap((s) => s.split(" ")));
console.log([1, 2, 3].flatMap((n) => (n % 2 ? [n, n * 10] : [])));
[ 1, 2, [ 3, [ 4 ] ] ] [ 1, 2, 3, 4 ] [ 'hello', 'world', 'hi' ] [ 1, 10, 3, 30 ]
Sorting objects and chaining
A comparator returns a negative number to put a first, a positive number to put b first, and 0 to keep their order (sort is stable). Combine criteria with ||: if the first difference is 0, the second decides. Because these methods return arrays, they can be chained into readable pipelines.
const team = [
{ name: "Ravi", score: 72 },
{ name: "Asha", score: 91 },
{ name: "Kiran", score: 72 },
];
// Highest score first; ties broken alphabetically by name. toSorted leaves team unchanged.
const ranking = team
.toSorted((a, b) => b.score - a.score || a.name.localeCompare(b.name))
.map((p, i) => `${i + 1}. ${p.name} (${p.score})`);
console.log(ranking.join("\n"));
1. Asha (91) 2. Kiran (72) 3. Ravi (72)
forEach vs map
forEach is for side effects and always returns undefined; map builds a new array from return values. An arrow function with braces needs return – without it every element maps to undefined.
const viaForEach = [1, 2, 3].forEach((n) => n * 2); // forEach always returns undefined
const viaMap = [1, 2, 3].map((n) => n * 2);
const forgotReturn = [1, 2, 3].map((n) => { n * 2; }); // braces need an explicit return
console.log(viaForEach, viaMap, forgotReturn);
undefined [ 2, 4, 6 ] [ undefined, undefined, undefined ]
Common mistakes
- reduce without an initial value – crashes on empty arrays and starts with an object instead of 0 for arrays of objects.
- Forgetting to return the accumulator – the next step receives undefined.
- Using forEach to build an array – it returns undefined; use map.
- map(parseInt) – the index becomes the radix.
- if (arr.filter(...)) – an empty array is still truthy; use some.
- find(...).prop without a check – find may return undefined.
- Sorting strings with a - b – NaN; use localeCompare.
Key points to remember
- map → same length; filter → subset; reduce → one value.
- Callbacks get (element, index, array).
- find returns an element or undefined; findIndex returns -1 when missing.
- some stops at the first true; every stops at the first false; every([]) is true.
- Always give reduce an initial value and return the accumulator.
- flat defaults to depth 1; flatMap = map + flat(1).
- forEach returns undefined and cannot be stopped.
Frequently asked questions
Are array methods slower than for loops?
Slightly, in tight hot loops, but rarely enough to matter. They are clearer and less error-prone. For very large data, combine steps in one reduce or loop instead of a long chain.
Can I use async functions with map?
map returns an array of promises; wrap it in await Promise.all(arr.map(async …)). forEach does not wait for async callbacks at all.
Should I use reduce for everything?
No. Use map, filter, find, some and every when they express the intent; reduce is best for building one value such as a sum, a count or a lookup object.
Where can I learn more?
Read map, filter and reduce and Higher-Order Functions in the JavaScript tutorial, then practise with the exercises below.