map() and the parseInt trap in JavaScript
Beginner · 3 min read
map is probably the array method you will use most. It takes a list and gives you a new list where every item has been changed in the same way: prices with tax added, names in capitals, numbers doubled. It also has a famous trap that turns up in interviews and in real bugs: ['1', '7', '11'].map(parseInt) does not give [1, 7, 11].
In this tutorial you will double some numbers, build labels using each item's position, and then work out exactly why the parseInt version goes wrong. You should know arrays, arrow functions and template literals (the backtick strings with ${...} in them).
How map calls your function
map calls your function once for each item and collects what it returns into a new array. The new array always has the same length as the old one.
The part people forget: map passes your function three arguments, not one. The item, its index, and the whole array.
['a', 'b'].map((value, index, array) => {
console.log(value, index, array.length);
return value;
});
// a 0 2
// b 1 2
Most of the time you only name the first one and ignore the rest. That is fine, as long as the function you hand over really does ignore them.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
13 map, and the parseInt trap
easyDouble every number, then build a label from each element and its index. Then explain why ['1', '7', '11'].map(parseInt) does not give [1, 7, 11].
Stuck? Three hints, smallest first
- 1. The callback is passed three arguments: value, index and the whole array.
- 2.
parseInttakes two: the text and a radix. Work out what the index is doing there. - 3.
map(Number)is safe becauseNumberonly looks at its first argument.
Step 1: double every number
const doubled = [1, 2, 3].map((n) => n * 2);
console.log(doubled); // [ 2, 4, 6 ]
map returns a new array. The original [1, 2, 3] is left alone.
Step 2: use the index
Name the second argument and you can use each item's position.
const labelled = ['a', 'b'].map((v, i) => `${i}:${v}`);
console.log(labelled); // [ '0:a', '1:b' ]
Step 3: the parseInt trap
parseInt turns text into a whole number, so passing it straight to map looks neat:
const broken = ['1', '7', '11'].map(parseInt);
console.log(broken); // [ 1, NaN, 3 ]
Only the first is right. The 7 became NaN ("not a number") and the 11 became 3.
Step 4: why it happens
parseInt takes two arguments: the text, and a radix, the number base to read it in (10 for normal numbers, 2 for binary, 16 for hex). map passes the index as the second argument, so the index lands in the radix slot. Here are the three calls map really made:
console.log(parseInt('1', 0)); // 1
console.log(parseInt('7', 1)); // NaN
console.log(parseInt('11', 2)); // 3
- Radix
0means "work it out yourself", which gives normal decimal, so'1'is 1. - Radix
1isn't a real number base, so the answer isNaN. - Radix
2is binary, and11in binary is 3 (one 2 plus one 1).
The third argument, the array, is ignored, because parseInt only uses two.
Step 5: two safe fixes
Number only looks at its first argument, so it ignores the index and array completely:
console.log(['1', '7', '11'].map(Number)); // [ 1, 7, 11 ]
Or wrap parseInt in your own arrow function, so you choose exactly what it receives:
console.log(['1', '7', '11'].map((s) => parseInt(s, 10))); // [ 1, 7, 11 ]
The two aren't identical: Number('12px') is NaN, while parseInt('12px', 10) reads the 12 and stops. Pick the one that suits your data. The general rule: only pass a named function straight to map when you know it uses one argument. Otherwise, wrap it.
Step 6: map never changes the original
const a = [1, 2];
const b = a.map((n) => n * 9);
console.log(a); // [ 1, 2 ]
console.log(b); // [ 9, 18 ]
console.log([1, 2, 3].map(() => 0).length); // 3
The input stays as it was, and the output always has one item per input item. If you want fewer items, that is filter's job, not map's.
The full solution
The panel doubles, labels, and then shows map(parseInt) next to the three calls it really makes, with map(Number) as the fix. Press Run to see the output.
const doubled = [1, 2, 3].map((n) => n * 2);
const labelled = ['a', 'b'].map((v, i) => `${i}:${v}`);
// parseInt(value, index): the index arrives as the radix.
const broken = ['1', '7', '11'].map(parseInt);
const fixed = ['1', '7', '11'].map(Number);
console.log('doubled :', doubled);
console.log('labelled:', labelled);
console.log('--- map(parseInt) hands the index over as the radix ---');
console.log('map(parseInt) :', broken);
console.log("parseInt('1', 0) ->", parseInt('1', 0), ' radix 0 means "guess", so decimal');
console.log("parseInt('7', 1) ->", parseInt('7', 1), ' radix 1 does not exist');
console.log("parseInt('11', 2) ->", parseInt('11', 2), ' binary 11 is 3');
console.log('map(Number) :', fixed);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('map applies the function to every element', doubled, [2, 4, 6]);
test('the callback receives the index', labelled, ['0:a', '1:b']);
test('map returns a new array and leaves the original alone', (() => { const a = [1, 2]; a.map((n) => n * 9); return a; })(), [1, 2]);
test('the result is always the same length', [1, 2, 3].map(() => 0).length, 3);
test('map(Number) converts cleanly', fixed, [1, 7, 11]);
test('map(parseInt) does not', broken.map(String), ['1', 'NaN', '3']);
test('because radix 1 is not a number system', Number.isNaN(parseInt('7', 1)), true);
test('and radix 2 reads "11" as binary', parseInt('11', 2), 3);
test('wrapping the call in your own arrow fixes it', ['1', '7', '11'].map((s) => parseInt(s, 10)), [1, 7, 11]);
map(parseInt) is the standard example of passing a function whose arity you have not checked. map calls back with three arguments, parseInt accepts two, so the index lands in the radix slot: index 0 means "work it out" (decimal), index 1 is not a valid radix at all, and index 2 makes '11' binary. Hence [1, NaN, 3].
map(Number) is safe because Number ignores extra arguments. The general rule: pass a named function to map only when you know it takes exactly one argument, otherwise wrap it in an arrow.
The assertion converts through String deliberately. JSON.stringify turns NaN into null, so comparing the raw arrays would have passed even if the middle value had been null or undefined.
Common mistakes
- Passing a two-argument function to
map.map(parseInt)hands the index over as the radix. Usemap(Number)ormap((s) => parseInt(s, 10)). - Using
mapjust to loop. If you don't use the returned array, useforEachorfor...ofinstead. - Forgetting to
returnin a block body.xs.map((n) => { n * 2 })gives an array ofundefined. With curly braces you must writereturn.
Try it yourself
- Turn
['lagos', 'abuja']into['Lagos', 'Abuja']withmap. - Predict what
['10', '10', '10'].map(parseInt)gives, then check it. - Use the index in
mapto number a list:['tea', 'milk']becomes['1. tea', '2. milk'].