JavaScript Array Methods: map, filter, reduce & Traps

Medium100% Free~20 mins#arrays#map#filter#reduce#forEach#polyfills#functional-programming
Interview Answer (30-Second Summary)

In JavaScript, custom array polyfills replicate native ECMAScript array methods: map returns a new array of transformed elements, filter returns elements satisfying a predicate, and reduce accumulates elements into a single value while properly handling sparse arrays and omitted initial values.

Key Learning Objectives
✓

Master core array iteration methods: map, filter, reduce, find, some, and every.

✓

Understand why forEach returns undefined and mutates state via side effects while map returns a new array.

✓

Recognize the arrow function block body return trap in filter and map callbacks.

✓

Grasp reduce accumulator initialization and behavior on empty arrays.

The Interview Problem

What is logged to the console when the following JavaScript code executes, and how do missing return statements and method return values affect the outcome?

1const nums = [1, 2, 3, 4];
2
3const mapped = nums.map((n) => {
4 if (n % 2 === 0) return n * 2;
5});
6
7const filtered = nums.filter((n) => {
8 n > 1;
9});
10
11const reduced = [1, 2, 3].reduce((acc, curr) => acc + curr, 10);
12
13const list = [1, 2];
14const forEachRet = list.forEach((n, i, arr) => {
15 arr[i] = n * 10;
16});
17
18console.log(
19 mapped.join(','),
20 filtered.length,
21 reduced,
22 String(forEachRet),
23 list.join(',')
24);
Predict Console Output
Interactive Challenge

Select the option that matches what this code prints to the console:

,4,,8 0 16 undefined 10,20

4,8 3 16 [10,20] 10,20

,4,,8 3 6 undefined 1,2

4,8 0 16 undefined 1,2

V8 Engine Execution Trace
Step 1 of 8 (Line 1)

nums array is initialized in heap memory with length 4.

Call Stack (Top = Active)
Global Execution Context
Lexical Scope / Bindings
nums:[1, 2, 3, 4]
Console Stream
> [empty]

JavaScript Array Methods Explained

Core Mental Models for JavaScript Array Methods

  1. map vs forEach:
    • Array.prototype.map(): A pure projection function. Transforms every element into a new element in a brand new array of identical length. If a branch omits return, that slot becomes undefined.
    • Array.prototype.forEach(): Designed solely for side effects (e.g. logging, API calls, mutating external data). It unconditionally returns undefined according to the ECMAScript specification.
  2. The Arrow Function Block Return Pitfall in filter:
    • Concise body: nums.filter(n => n > 1) has an implicit return.
    • Block body: nums.filter(n => { n > 1; }) contains an expression statement without the return keyword. It returns undefined, which coerces to false, discarding every element.
  3. reduce Accumulator Initialization Rules:
    • arr.reduce(callback, initialValue): If initialValue is provided, acc starts at initialValue and the callback runs arr.length times.
    • If initialValue is omitted, acc starts as arr[0], the first iteration starts at index 1, and the callback runs arr.length - 1 times.
    • Fatal Edge Case: Calling reduce() without an initial value on an empty array ([].reduce(...)) throws TypeError: Reduce of empty array with no initial value.
Common Traps & Mistakes

Calling `[].reduce((acc, curr) => acc + curr)` without an initial value, resulting in an unhandled TypeError crash in production.

Confusing mutating methods (`push`, `pop`, `shift`, `unshift`, `splice`, `sort`, `reverse`) with non-mutating methods (`map`, `filter`, `slice`, `concat`, `toSorted`, `toReversed`).

Expecting `forEach` to break early using `return` or `break`. `return` only exits the current callback iteration, and `break` is a syntax error inside a function callback. Use `for...of`, `some()`, or `find()` instead.

FAANG Follow-Up Probes
Probe #1

How would you implement a polyfill for Array.prototype.reduce that correctly handles sparse arrays and missing initialValue?

Probe #2

Why can you not stop or break out of an Array.prototype.forEach loop, and how do you achieve short-circuiting with some() or every()?

Probe #3

What are the newly standardized ECMAScript immutable array methods (toSorted, toReversed, toSpliced, with), and how do they benefit React state updates?

JavaScript Array Methods Interview Questions

Key interview inquiries, edge cases, and architectural follow-ups for JavaScript Array Methods.

Q1.
What is the difference between Array.prototype.map and Array.prototype.forEach?

map returns a brand new array containing the results of calling the callback on each element, preserving length. forEach always returns undefined and is used strictly for side effects without returning transformed data.

If initialValue is not provided, the polyfill must find the first non-empty slot in the array as the accumulator and begin iteration at the subsequent index. If the array is empty and no initialValue is provided, it must throw a TypeError.

Native methods use Object.prototype.hasOwnProperty or the "in" operator (index in array) to check if an index actually exists. Callbacks are never executed on unassigned holes, preserving sparse structure.

If a thisArg is supplied, the polyfill invokes the callback using callback.call(thisArg, element, index, array) to ensure correct context binding for regular callback functions.

All three methods operate in O(N) time where N is the array length. map and filter require O(N) space to allocate the returned array; reduce requires O(1) auxiliary space beyond the accumulator value.

Arrow functions with curly braces require an explicit return keyword; omitting return causes the callback to return undefined for every element, resulting in an array of undefined values.

More JavaScript interview questions for freshers