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.

Map method of Array

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

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.

--

--

--

Loves coding and enjoys learning new technologies. Website: https://.yuvrajpatil.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Travel-Blog Project

Seamless animated page transitions in Jekyll with Animate.css

5 Simple Things You Can Do To Make Your Website Standout

Upload Image: [MERN stack] via Multer

Calculate Time Difference Between Two Dates in Uipath

async/await in-depth: Part 1

Learn NodeJS Basics & Build a Simple Web Server

10 Effective Topics of Javascript Types, eval, Delete, timeout, & Scopes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yuvraj Patil

Yuvraj Patil

Loves coding and enjoys learning new technologies. Website: https://.yuvrajpatil.com

More from Medium

Temporal Dead Zone

Temporal Dead Zone

What is Nullish Coalescing Operator

Why Lodash is not a foolproof Comparer for JavaScript objects?

JS學習筆記(1)