Arrays and Iteration
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Transform data with map, filter and reduce.
- Explain the difference between mutating and non-mutating array methods.
- Iterate with for..of and the iterable protocol.
Overview
#Arrays are ordered lists
An array is an object whose integer keys are indices and whose length tracks the highest index plus one. Arrays have a rich set of methods, and the ones you will use most are map, filter, reduce, find, some, every and slice.
map, filter and reduce
map builds a new array by applying a function to every element. filter builds a new array of elements that pass a predicate. reduce folds the array into a single value using an accumulator. These three cover most data transforms.
const nums = [1, 2, 3, 4];
const doubled = nums.map((n) => n * 2);
const evens = nums.filter((n) => n % 2 === 0);
const sum = nums.reduce((total, n) => total + n, 0);
console.log(doubled, evens, sum); // [2,4,6,8] [2,4] 10
Mutating versus non-mutating
map, filter, slice and concat return new arrays and leave the original alone. push, pop, splice, sort and reverse mutate in place. Mixing them up is a common source of bugs, especially when state is shared. sort mutating in place surprises people who expect a sorted copy.
Iterables and for..of
An iterable is an object with a method at the symbol key Symbol.iterator that returns an iterator with a next method. Arrays, strings, maps and sets are iterable. for..of consumes the iterator, and spread and destructuring use the same protocol.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst result = [1, 2, 3].map((n) => { n * 2; }); console.log(result[0], result.length);Exercise 2Explain
Explain what the accumulator is in this reduce call and why the initial value matters.
starter.javascriptconst sum = [1, 2, 3].reduce((acc, n) => acc + n, 0);Reveal the reference answer
reference.javascriptThe accumulator is the running value carried between iterations. It starts at the initial value 0 and each iteration returns the next accumulator. Providing 0 guarantees a number result even for an empty array; without an initial value reduce uses the first element and throws on an empty array.Authored expected output: 6
The initial value sets the type and the empty-array behavior of reduce. Omitting it is a frequent source of TypeErrors.
Exercise 3Implement
Implement `groupBy(items, keyFn)` that returns an object mapping each key to the array of items with that key. Running `console.log(groupBy([1, 2, 3, 4], (n) => (n % 2 ? 'odd' : 'even')));` should print `{ odd: [1, 3], even: [2, 4] }`.
starter.javascriptfunction groupBy(items, keyFn) { // your code here }Reveal the reference answer
reference.javascriptfunction groupBy(items, keyFn) { return items.reduce((groups, item) => { const key = keyFn(item); (groups[key] ||= []).push(item); return groups; }, {}); }Authored expected output: { odd: [1, 3], even: [2, 4] }
reduce carries the growing object as the accumulator. The logical OR assignment creates the bucket on first use and pushes into it on every visit, producing one array per key.
Exercise 4Debug
This function is meant to return a sorted copy but mutates the caller's array. Fix it so the input is unchanged.
starter.javascriptfunction sortedCopy(numbers) { return numbers.sort((a, b) => a - b); } const input = [3, 1, 2]; console.log(sortedCopy(input), input);Reveal the reference answer
reference.javascriptfunction sortedCopy(numbers) { return [...numbers].sort((a, b) => a - b); } const input = [3, 1, 2]; console.log(sortedCopy(input), input);Authored expected output: [1, 2, 3] [3, 1, 2]
sort mutates the array it is called on. Copying with the spread operator first sorts a new array and leaves the caller's array in its original order.
Exercise 5Test
Write tests for a `chunk(items, size)` function that splits an array into groups.
starter.javascriptfunction chunk(items, size) { const out = []; for (let i = 0; i < items.length; i += size) { out.push(items.slice(i, i + size)); } return out; }Reveal the reference answer
reference.javascriptconst assert = (cond, label) => { if (!cond) throw new Error(label); }; assert(JSON.stringify(chunk([1, 2, 3, 4, 5], 2)) === JSON.stringify([[1, 2], [3, 4], [5]]), 'uneven tail'); assert(JSON.stringify(chunk([], 3)) === JSON.stringify([]), 'empty input'); assert(JSON.stringify(chunk([1], 5)) === JSON.stringify([[1]]), 'size larger than input'); console.log('chunk tests passed');Authored expected output: chunk tests passed
The tests cover an uneven final group, an empty input and a size larger than the array, which are the three cases most likely to break a slicing loop.
Exercise 6Interview
Explain the difference between map, forEach and reduce, and when you would choose each.
starter.javascriptconst nums = [1, 2, 3];Reveal the reference answer
reference.javascriptmap returns a new array of the same length and is for transforming every element. forEach returns undefined and is for side effects such as logging or mutating external state. reduce folds the array into any single value, including a number, string, object or another array, and is the most general of the three. Choose map for transforms, forEach for side effects only, and reduce when the result is a single accumulated value.The answer should emphasize the return contract of each method, since that is what determines correctness and readability.
Common misconceptions
#- map returns the original array when the callback has no return.
- sort returns a new sorted array and leaves the original unchanged.
- for..of and for..in iterate the same thing.
Follow-up practice
#- javascript-foundations-async-event-loop
- javascript-foundations-metaprogramming
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.