Magic of Array’s map method with parseInt

Photo by bruce mars on Unsplash
["1", "2", "111"].map(parseInt);  // returns [1, NaN, 7]

Have you ever tried passing parseInt to array’s map method ?

If not yet, I will say try it now. It’s very interesting.

When we try it for first time, it looks very confusing but once we understand the logic, it becomes easy to understand.

To understand how this works we need to understand how map method and parseInt work.

It creates a new array after executing a callback function on every array elements. Three parameters are passed to that callback function.

  • Current Object
  • Current Index
  • Source Array

In our case that callback function is parseInt. So parseInt will be called on each array element and it’s result will be added in newly created array.

Hence our code

["1", "2", "111"].map(parseInt);

will be executed like

parseInt("1", 0, ["1", "2", "111"]);         // 1
parseInt("2", 1, ["1", "2", "111"]); // NaN
parseInt("111", 2, ["1", "2", "111"]); // 7

parseInt method is used to convert string into the integer. We might have used this method lots of time but without using it’s second (optional) parameter. This second parameter is used to specify radix (number system).

So when parseInt("1", 0, ["1", "2", "111"]); is called, it tries to convert
"1" into integer with radix 0, hence it returns 1.

Similarly parseInt("2", 1, ["1", "2", "111"]); tries to convert
"2" into integer with radix 1, hence it returns NaN.

Similarly parseInt("111", 2, ["1", "2", "111"]); tries to convert
"111" into integer with radix 2, hence it returns 7.

Hence ["1", "2", "111"].map(parseInt); returns [1, NaN, 7]

Conclusion

parseInt can get tricky if passed to higher order functions like Array’s map. We should take extra care while passing parseInt as a callback function.

Programmer who loves coding and enjoys learning new technologies. 8 years of experience in JavaScript development. Website: http://www.yuvrajpatil.com