Sub topic 10
Common Pitfalls: map(parseInt), Side Effects, and Sparse Arrays
This chapter assumes you already know how map, filter, and reduce work, that callbacks receive (element, index, array), and that these methods return new arrays instead of changing the original. Each bug below comes from code that looks correct and runs without errors but returns the wrong result. There are three groups of bugs:
- Callbacks that receive more arguments than they expect.
- Callbacks that change data they should only read.
- Arrays with holes, which the methods treat differently from
undefined.
Pitfall 1: Passing a Function Reference That Takes Extra Parameters
The classic: `map(parseInt)`
Passing a named function straight to map looks tidy:
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
console.log(['1', '2', '3'].map(s => parseInt(s, 10))); // [1, 2, 3]map calls its callback with three arguments: the element, the index, and the array. parseInt accepts two parameters, (string, radix), so the index ends up as the radix. Here is what actually runs:
| Call made by `map` | Radix meaning | Result |
|---|---|---|
| `parseInt('1', 0)` | 0 means "guess", which is base 10 here | `1` |
| `parseInt('2', 1)` | Base 1 is invalid | `NaN` |
| `parseInt('3', 2)` | `3` is not a binary digit | `NaN` |
The third argument (the array) is ignored because parseInt declares only two parameters. JavaScript never complains about extra arguments, so nothing warns you.
The fix and its alternatives
Wrap the call in an arrow function so you control exactly which arguments reach it. The other options parse differently, so pick one on purpose:
const inputs = ['42', '12px', '', '0x1F'];
console.log(inputs.map(s => parseInt(s, 10))); // [42, 12, NaN, 0]
console.log(inputs.map(Number)); // [42, NaN, 0, 31]
console.log(inputs.map(parseFloat)); // [42, 12, NaN, 0]Number is safe to pass directly because it uses only its first argument. It is stricter than parseInt, though: it rejects '12px', turns '' into 0, and reads '0x1F' as hexadecimal. parseFloat also takes only one parameter, so passing it directly works too.
The same bug in your own code
This problem is not limited to built-in functions. Any function with an optional second parameter can be hit:
function formatPrice(amount, currency = 'USD') {
return `${amount.toFixed(2)} ${currency}`;
}
const amounts = [5, 12.5, 30];
console.log(amounts.map(formatPrice));
// ['5.00 0', '12.50 1', '30.00 2'] (index used as currency)
console.log(amounts.map(a => formatPrice(a)));
// ['5.00 USD', '12.50 USD', '30.00 USD']The default value only applies when the argument is undefined. map always passes an index, so the default never kicks in. There is also a maintenance risk. A function that works with point-free style today (passed by name, like map(fn)) can break later when someone adds an optional parameter to it.
Pitfall 2: Side Effects Inside Callbacks
Mutating the objects you map over
map returns a new array, but the elements in it are the same object references as in the original. If the callback changes an object, the original data changes too:
const users = [{ name: 'Ada', active: false }];
const bad = users.map(u => {
u.active = true; // writes to the shared object
return u;
});
console.log(users[0].active); // true (original changed)
console.log(bad[0] === users[0]); // true (same object)
const users2 = [{ name: 'Grace', active: false }];
const good = users2.map(u => ({ ...u, active: true }));
console.log(users2[0].active); // false
console.log(good[0] === users2[0]); // falseSpread is shallow
{ ...u } copies only the top-level properties. Nested objects stay shared:
const people = [{ name: 'Linus', address: { city: 'Helsinki' } }];
const shallow = people.map(p => ({ ...p }));
shallow[0].address.city = 'Portland';
console.log(people[0].address.city); // 'Portland' (leaked through)
const people2 = [{ name: 'Linus', address: { city: 'Helsinki' } }];
const deep = people2.map(p => ({
...p,
address: { ...p.address, city: 'Portland' }
}));
console.log(people2[0].address.city); // 'Helsinki'Copy every level you plan to change. If you need a full independent copy of plain data, structuredClone(obj) makes one. It costs more, so use it only when you actually need a deep copy.
Using map when you mean forEach
If you ignore the array that map returns, you are using map only for its side effects:
const ids = [1, 2, 3];
// Misleading: builds and throws away [undefined, undefined, undefined]
ids.map(id => console.log('processing', id));
// Clear intent
ids.forEach(id => console.log('processing', id));Readers expect map to transform data. Linters such as ESLint's array-callback-return rule flag a map callback that returns nothing.
Mutating the array during iteration
map, filter, and reduce read the array's length once, before the first callback runs. They then check each index when they reach it. That leads to some surprising behavior:
const arr = [1, 2, 3];
const out = arr.map((x, i, a) => {
if (i === 0) {
a.push(99); // appended: never visited
a[2] = 30; // changed before it was visited: new value seen
}
return x * 10;
});
console.log(out); // [10, 20, 300]
console.log(arr); // [1, 2, 30, 99]If the callback deletes an element it has not reached yet, map skips that element. Don't depend on any of this behavior. Treat the third callback argument as read-only.
A fresh accumulator for reduce
Changing the accumulator inside reduce is fine when the initial value is created fresh for each call. It becomes a bug when that object is shared:
const shared = {};
const countA = ['x', 'y'].reduce((acc, k) => { acc[k] = 1; return acc; }, shared);
const countB = ['z'].reduce((acc, k) => { acc[k] = 1; return acc; }, shared);
console.log(countA === countB); // true
console.log(countB); // { x: 1, y: 1, z: 1 }Write the literal {} or [] directly in the reduce call so that every call starts with a new object.
Pitfall 3: Sparse Arrays
Holes are not undefined
A sparse array has missing indices, called holes. A hole is an index with no property at all. An element whose value is undefined is different: the property exists and holds undefined. You can tell them apart with the in operator:
const sparse = [1, , 3]; // hole at index 1
const dense = [1, undefined, 3];
console.log(sparse.length, dense.length); // 3 3
console.log(1 in sparse); // false
console.log(1 in dense); // trueHoles come from array literals with empty slots, new Array(n), delete arr[i], and setting arr.length larger than it is.
How each method treats holes
map, filter, reduce, forEach, some, every, and flatMap check whether each index exists and skip the holes. Each method handles the output differently:
const sparse = [1, , 3];
console.log(sparse.map(x => x * 2)); // [ 2, <1 empty item>, 6 ]
console.log(sparse.map((x, i) => i)); // [ 0, <1 empty item>, 2 ]
console.log(sparse.filter(() => true)); // [1, 3]
let calls = 0;
const sum = sparse.reduce((acc, x) => { calls++; return acc + x; }, 0);
console.log(sum, calls); // 4 2
console.log(sparse.find(x => x === undefined)); // undefined (hole visited)
console.log([...sparse]); // [1, undefined, 3]| Operation | Hole behavior |
|---|---|
| `map` | Skips the callback and keeps the hole in the result |
| `filter` | Skips the hole, so the result has no holes |
| `reduce`, `reduceRight` | Skips the hole and does not count it as a step |
| `forEach`, `some`, `every`, `flatMap` | Skip the hole |
| `find`, `findIndex` | Visit the hole as `undefined` |
| `for...of`, spread, `Array.from` | Read the hole as `undefined` |
Code that counts with reduce gets an answer that is too low. Code that compares result.length from map with the number of callback calls gets numbers that don't match. Because filter drops holes silently, the indices in its output no longer line up with the input.
The `new Array(n).map` trap
The most common sparse-array bug comes from trying to build a range of numbers:
console.log(new Array(3).map((_, i) => i)); // [ <3 empty items> ]
console.log(Array.from({ length: 3 }, (_, i) => i)); // [0, 1, 2]
console.log([...Array(3)].map((_, i) => i)); // [0, 1, 2]
console.log(Array(3).fill(0).map((_, i) => i)); // [0, 1, 2]new Array(3) sets the length to 3 but creates no elements, so map has nothing to visit. Array.from with a length object is the clearest fix, and it maps in the same step. Spreading and fill both work by turning the holes into real undefined (or 0) values first.
Quick Checklist
- Wrap function references in an arrow function unless the function uses only one argument.
- Return new objects from
map, and copy every nested level you change. - Use
forEachfor side effects andmapfor transformations. - Never change the array you are iterating over.
- Create the
reduceinitial value inside the call. - Build sequences with
Array.from({ length: n }, fn), notnew Array(n).map.
Exercise
What does ['10', '10', '10'].map(parseInt) return, and why?
Show answer
It returns [10, NaN, 2]. The calls are parseInt('10', 0), where radix 0 means base 10, giving 10. Next is parseInt('10', 1), where base 1 is invalid, giving NaN. Last is parseInt('10', 2), which reads '10' in binary, giving 2. Use .map(s => parseInt(s, 10)) to get [10, 10, 10].
Exercise
A teammate writes const grid = new Array(4).map(() => []); and then grid[0].push('x') throws a TypeError. Explain the cause and write a fix that gives each row its own array.
Show answer
new Array(4) creates four holes. map skips holes, so the callback never runs and grid[0] is undefined. Fix it with const grid = Array.from({ length: 4 }, () => []);. Avoid new Array(4).fill([]), because fill puts the same array object in every slot, so a push to one row shows up in all rows.
Exercise
Given const items = [{ id: 1, tags: ['a'] }];, does const copy = items.map(i => ({ ...i })); copy[0].tags.push('b'); change items? How would you add the tag without changing the original?
Show answer
Yes. Spread copies only the top level, so copy[0].tags and items[0].tags are the same array. To keep the original unchanged, copy the nested array too: items.map(i => ({ ...i, tags: [...i.tags, 'b'] })).