map, filter & reduce

Published by Brayan K

These three array methods are the heart of modern, professional JavaScript. They let you express "transform this", "keep these", and "summarise that" declaratively — you describe the result instead of writing fiddly for loops with index bookkeeping.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose the shape of the result before choosing a method

Map transforms values into a new array, filter selects existing values into a new array, and reduce carries a result through the visited values. Choose based on the result you need. A loop is still useful when it expresses the work more clearly; these methods are not a requirement for making code professional.

const quantities = [1, 3, 2];
const doubled = quantities.map(value => value * 2);
const large = quantities.filter(value => value >= 2);
const total = quantities.reduce((sum, value) => sum + value, 0);
// Inspect each result separately before combining operations.
console.log(JSON.stringify(doubled));
console.log(JSON.stringify(large));
console.log(total);
console.log(JSON.stringify(quantities));

// ✅ Expected output:
// [2,6,4]
// [3,2]
// 6
// [1,3,2]

A callback is the function the method invokes for each visited value. Functions owns function inputs and returns; here the important question is what each array method does with that return value.

Map collects the callback result, not the expression you forgot to return

An expression-bodied arrow returns its expression. A braced function body needs an explicit return. If a callback finishes without returning a value, map puts undefined into the corresponding result position rather than guessing which calculation you intended.

const values = [2, 4];
const doubled = values.map(value => {
  value * 2;
});
console.log(doubled.length);
console.log(doubled[0] === undefined);
console.log(doubled[1] === undefined);

// ✅ Expected output:
// 2
// true
// true
const values = [2, 4];
const doubled = values.map(value => {
  return value * 2;
});
const records = values.map(value => ({ quantity: value }));
console.log(JSON.stringify(doubled));
console.log(JSON.stringify(records));

// ✅ Expected output:
// [4,8]
// [{"quantity":2},{"quantity":4}]

The parentheses around the object expression distinguish it from a function-body block. Keep the returned value visible in a callback that is meant to transform data; logging a value is not the same as returning it.

function double(value) {
  return value * 2;
}
const values = [1, 2];
console.log(values.map(double(2)));

// ✅ Expected error:
// TypeError: number 4 is not a function

Double is invoked before map receives its argument in the failing example. Pass double itself, or a wrapper that calls it for each value, when the method needs a function.

Filter keeps the original element when its test is truthy

Filter interprets the callback result as a keep-or-drop decision. It does not replace an element with the callback result. A numeric calculation can accidentally act as a predicate, with zero discarded and other nonzero results accepted.

const values = [0, 1, 2];
const selected = values.filter(value => value * 2);
const transformed = values.map(value => value * 2);
console.log(JSON.stringify(selected));
console.log(JSON.stringify(transformed));

// ✅ Expected output:
// [1,2]
// [0,2,4]
const values = [-2, 0, 3, 5];
const nonnegative = values.filter(value => value >= 0);
const impossible = values.filter(value => value > 10);
console.log(JSON.stringify(nonnegative));
console.log(JSON.stringify(impossible));

// ✅ Expected output:
// [0,3,5]
// []

Use a condition that names the acceptance rule, especially when zero is valid data. Type Coercion (== vs ===) owns truthiness; a false-looking string is not automatically a false predicate result.

A new array does not guarantee untouched source objects

Map and filter produce new arrays, but callbacks can still mutate input objects or other outside state. Returning the same object from map preserves that object reference. The method does not undo changes made by your callback.

const items = [{ quantity: 2 }, { quantity: 3 }];
const doubled = items.map(item => {
  item.quantity *= 2;
  return item;
});
console.log(JSON.stringify(items));
console.log(doubled === items);
console.log(doubled[0] === items[0]);

// ✅ Expected output:
// [{"quantity":4},{"quantity":6}]
// false
// true
const items = [{ quantity: 2 }, { quantity: 3 }];
const doubled = items.map(item => ({
  ...item,
  quantity: item.quantity * 2
}));
console.log(JSON.stringify(items));
console.log(JSON.stringify(doubled));
console.log(doubled[0] === items[0]);

// ✅ Expected output:
// [{"quantity":2},{"quantity":3}]
// [{"quantity":4},{"quantity":6}]
// false
const items = [{ quantity: 2 }, { quantity: 0 }];
const selected = items.filter(item => item.quantity > 0);
selected[0].quantity = 9;
console.log(items[0].quantity);
console.log(selected === items);

// ✅ Expected output:
// 9
// false

The new-record version copies only the shown level. Spread & Rest Operators owns shallow copying and nested updates; choosing map instead of a loop does not itself create immutability.

A callback can receive more arguments than you expected

Map and filter pass the current value, its index and the source array to their callback. A function designed for a different argument list may therefore interpret those extra values unexpectedly. A small wrapper can make the intended inputs explicit.

const values = ["A17", "B24"];
const labels = values.map((value, index, array) => {
  console.log(value, index, array === values);
  return index + ":" + value;
});
console.log(JSON.stringify(labels));

// ✅ Expected output:
// A17 0 true
// B24 1 true
// ["0:A17","1:B24"]
const raw = ["10", "11", "12"];
const wrong = raw.map(parseInt);
for (const value of wrong) {
  console.log(value);
}
const fixed = raw.map(value => parseInt(value, 10));
console.log(JSON.stringify(fixed));

// ✅ Expected output:
// 10
// NaN
// 1
// [10,11,12]

ParseInt interprets its second argument as a radix, while map supplies an index in that position. Numbers & Math owns parsing behaviour; the callback lesson here is to check the complete parameter contract before passing an existing function directly.

Map also does not wait for an async callback to resolve: the callback returns a promise as its value. Async/Await owns waiting for asynchronous results and handling their failures.

Empty slots are skipped, but explicit undefined values are visited

These methods visit assigned array indexes, not every possible index below length. Map preserves holes in the resulting array; filter produces a compact selection of the values it visited. A present element with value undefined is different from an absent slot.

const values = [2, , 6];
let visits = 0;
const doubled = values.map(value => {
  visits += 1;
  return value * 2;
});
console.log(values.length, visits, doubled.length);
console.log(Object.hasOwn(doubled, 1));
console.log(JSON.stringify(values.filter(() => true)));
let explicitVisits = 0;
[undefined].map(() => { explicitVisits += 1; });
console.log(explicitVisits);

// ✅ Expected output:
// 3 2 3
// false
// [2,6]
// 1

Use an explicit representation for missing data when every position needs processing. Arrays and Objects owns array structure; a promise of one callback per numeric position would be wrong for a sparse array.

Reduce carries the value returned by each step

With an initial value, the first callback receives that value as its accumulator and the first visited element as its current value. Every callback return becomes the next accumulator. Trace those inputs before compressing a reduction into a one-line expression.

const values = [3, 5, 2];
const total = values.reduce((accumulator, value, index) => {
  const next = accumulator + value;
  console.log(index, accumulator, value, next);
  return next;
}, 0);
console.log("total", total);

// ✅ Expected output:
// 0 0 3 3
// 1 3 5 8
// 2 8 2 10
// total 10
const total = [2, 3].reduce((accumulator, value) => {
  console.log("received", accumulator);
  accumulator += value;
}, 0);
console.log("result", total);

// ✅ Expected output:
// received 0
// received undefined
// result undefined

The callback in the second example returns undefined because it has no return statement. A local assignment does not tell reduce what to carry forward. Return the intended next accumulator on every path.

Choose an initial value that makes empty input meaningful

Without an initial value, reduce takes its starting accumulator from the first visited element and begins callbacks after that element. An array with no visited elements has no starting value and throws. Providing an initial value makes the empty-input result explicit.

const values = [];
console.log(values.reduce((sum, value) => sum + value));

// ✅ Expected error:
// TypeError: Reduce of empty array with no initial value
console.log([].reduce((sum, value) => sum + value, 0));
let calls = 0;
const single = [7].reduce((sum, value) => {
  calls += 1;
  return sum + value;
});
console.log(single, calls);
const withInitial = [7].reduce((sum, value) => {
  calls += 1;
  return sum + value;
}, 0);
console.log(withInitial, calls);

// ✅ Expected output:
// 0
// 7 0
// 7 1

Zero is suitable for a numeric sum, but it is not a universal initial value for every reduction. Choose the accumulator type and identity that fit the result, and decide what an empty input should mean.

The accumulated result can be a record

Reduce returns whatever accumulator your callback carries, not necessarily a number. This example returns a fresh summary record at each step so its count and total responsibilities are visible.

const quantities = [2, 4, 1];
const summary = quantities.reduce((accumulator, quantity) => ({
  count: accumulator.count + 1,
  total: accumulator.total + quantity
}), { count: 0, total: 0 });
console.log(JSON.stringify(summary));

// ✅ Expected output:
// {"count":3,"total":7}

Keep an ordinary loop when it communicates the update more clearly. Advanced Array & Object Transformations owns larger grouping, indexing and flattening operations; they do not all need to be packed into one reducer.

Check the result between stages of a chain

A chain reads from left to right: each array result becomes the input to the following method. During debugging, give those intermediate arrays names and inspect them before checking the final total.

const evens = [1, 2, 3, 4, 5].filter(value => value % 2 === 0);
const doubled = evens.map(value => value * 2);
const total = doubled.reduce((sum, value) => sum + value, 0);
console.log(JSON.stringify(evens));
console.log(JSON.stringify(doubled));
console.log(total);

// ✅ Expected output:
// [2,4]
// [4,8]
// 12

Decide whether a predicate should see the original or transformed values. Changing method order can change the meaning of the decision as well as the amount of work; there is no general rule that filter and map can be swapped freely.

Complete a filter, a transformation and a total

Keep only positive values, double each retained value, then add the transformed values starting from zero. Fill the three callback expressions using the literal hints. Each method has one distinct responsibility.

const values = [3, -1, 0, 4];
const total = values
  .filter(value => ___)
  .map(value => ___)
  .reduce((sum, value) => ___, 0);
// 👉 replace ___ with value > 0
// 👉 replace ___ with value * 2
// 👉 replace ___ with sum + value
console.log(total);

// ✅ Expected output:
// 14

Total only the orders that are ready to pack

Write readyTotal for an array of order records with ready, quantity and unitPrice fields. Keep records that are ready and have a positive quantity, calculate each retained line total, then sum those totals. Prices are fixed integer minor units in this exercise, and inputs already have the documented types. Print the total for the supplied orders, an empty array and an array with no ready orders. Do not change the records.

function readyTotal(orders) {
  return orders
    .filter(order => order.ready && order.quantity > 0)
    .map(order => order.quantity * order.unitPrice)
    .reduce((sum, lineTotal) => sum + lineTotal, 0);
}
const orders = [
  { ready: true, quantity: 2, unitPrice: 150 },
  { ready: false, quantity: 10, unitPrice: 999 },
  { ready: true, quantity: 3, unitPrice: 200 },
  { ready: true, quantity: 0, unitPrice: 500 }
];
console.log(readyTotal(orders));
console.log(readyTotal([]));
console.log(readyTotal([{ ready: false, quantity: 2, unitPrice: 150 }]));
console.log(JSON.stringify(orders));

// ✅ Expected output:
// 900
// 0
// 0
// [{"ready":true,"quantity":2,"unitPrice":150},{"ready":false,"quantity":10,"unitPrice":999},{"ready":true,"quantity":3,"unitPrice":200},{"ready":true,"quantity":0,"unitPrice":500}]

The initial zero gives the two empty-selection cases a defined result. The callbacks read the input fields and return values without assigning to the records. If input validation is needed, establish that contract separately before using this calculation.

References: MDN documents the callback and iteration contracts for map, filter, and reduce.

Practice quiz

What does this complete program print? const result = [2, 3].map(value => { value * 2; }); console.log(result[0] === undefined, result[1] === undefined);

  • true true
  • false false
  • true false
  • false true

Answer: true true. The braced callbacks have no return statement, so both result elements are undefined.

What does this complete program print? console.log(JSON.stringify([0, 1, 2].filter(value => value * 2)));

  • [0,2,4]
  • [1,2]
  • [0,1,2]
  • [2,4]

Answer: [1,2]. Filter retains the original elements with truthy test results; it does not return the calculated test values.

What does this complete program print? const items = [{ count: 1 }]; const result = items.map(item => { item.count = 9; return item; }); console.log(items[0].count, result[0] === items[0]);

  • 1 false
  • 1 true
  • 9 true
  • 9 false

Answer: 9 true. The callback mutates and returns the same object, even though map creates a new outer array.

Which error ends this program? console.log([].reduce((sum, value) => sum + value));

  • ReferenceError: sum is not defined
  • TypeError: sum is not a function
  • RangeError: Invalid array length
  • TypeError: Reduce of empty array with no initial value

Answer: TypeError: Reduce of empty array with no initial value. With no initial accumulator and no visited elements, reduce has no starting value and throws.

What does this complete program print? let calls = 0; const result = [8].reduce((sum, value) => { calls++; return sum + value; }); console.log(result, calls);

  • 8 0
  • 8 1
  • 0 0
  • 0 1

Answer: 8 0. The sole element becomes the accumulator, leaving no later element for a callback invocation.

What does this complete program print? let visits = 0; const result = [2, , 6].map(value => { visits++; return value; }); console.log(visits, result.length);

  • 3 3
  • 2 3
  • 2 2
  • 3 2

Answer: 2 3. Map skips the empty slot while preserving the array length and the hole.

What does this complete program print? const result = [1, 2, 3, 4, 5] .filter(value => value % 2 === 0) .map(value => value * 2) .reduce((sum, value) => sum + value, 0); console.log(result);

  • 30
  • 6
  • 12
  • 24

Answer: 12. The selected even values are doubled and then added; inspecting each stage prevents an unrelated total from being assumed.

What does this complete program print? const total = [2, 3].reduce((sum, value) => { sum += value; }, 0); console.log(total);

  • 5
  • 0
  • NaN
  • undefined

Answer: undefined. The callback never returns its updated local sum, so reduce receives undefined as each returned accumulator.

Continue this course

Related lessons