This page looks best with JavaScript enabled

Use Right Syntax for a Map

 ·   ·  ☕ 2 min read

Map on an array is simple enough -

1
2
3
const ran = ["1", "3", "5"].map(val => Number(val));
console.log("ran: ", ran);
// ran:  [ '1', '3', '5' ]

map will specify one element at a time, which is passed to the callback function as val.

Let’s say, we ignore the val.

1
2
3
const ranToo = ["1", "3", "5"].map(Number);
console.log("ranToo: ", ranToo);
// [ 1, 3, 5 ]

The above code works too. map takes a callback function and runs it on every element, so no problem with the above code.

Now, consider the below.

1
2
3
const ranThree = ["1", "3", "5"].map(parseInt);
console.log("ranThree: ", ranThree);
// [ 1, NaN, NaN ]

Oops. Let’s see what map passes to the callback function.

1
2
3
4
5
6
function printMe(val) {
  console.log(val);
  // 1 3 5
}

const ranCheck = ["1", "3", "5"].map(printMe);

This is not a problem, so let’s expand our horizon.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function printMe(val1, val2, val3) {
  console.log(val1, val2, val3);
}

const ranCheck = ["1", "3", "5"].map(printMe);
/*
1 0 [ '1', '3', '5' ]
3 1 [ '1', '3', '5' ]
5 2 [ '1', '3', '5' ]
*/

We can see what’s happening - there are multiple arguments passed everywhere, and there may be an issue with the callback and the way map has passed the arguments.

Let’s compare notes with the definition of a map. Map accepts a callback function, values (one at a time), and passes across the values to the callback function.

parseInt accepts an input to parse, and radix (defaulted to 10). Radix represents the base of the number in mathematics.

Therefore, in our case parseInt is being passed both the actual value and index.

  1. 1, 0
  2. 3, 1
  3. 5, 2

parseInt sees this and decides that the value passed is not a real number since 3 and 5 do not exist in the radix 1 and 2 respectively. The evaluation will result in -

1
2
3
console.log(parseInt("1", 0)); // 1, radix -> an octal number
console.log(parseInt("3", 1)); // NaN, what is base 1 and what is 3 in base 1?
console.log(parseInt("5", 2)); // NaN, 5 is not valid in binary

Avoiding these errors

Avoid the above errors and the resulting frustration by always using an anon function.

1
2
3
const ranInts = ["1", "3", "5"].map(val => parseInt(val));
console.log("ranInts: ", ranInts);
// ranInts:  [ 1, 3, 5 ]

The code is explicit in specifying the arguments and is highly readable.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things