DEV Community

Cover image for Array.map & parseInt in JavaScript
Jules Kulcsar
Jules Kulcsar

Posted on

Array.map & parseInt in JavaScript

I saw something today posted by someone on Twitter and I thought to write a short post about it in a simple manner as the newbie that I am myself.

If you're new to JavaScript, I am sure many things look like they make sense, only to realize that the output of your code is something totally unexpected.

What I saw was this:

['1', '2', '10'].map(parseInt)

We know that:

  1. parseInt function parses a string and returns an integer.
  2. map function creates a new array with the results of calling a function for every array element.

Now, if you expected the above to output this:

[1, 2, 10]

it actually outputs this:

[1, NaN, 2]

This is where understanding how things behave in Javascript will come very handy.

We know that parseInt expects 2 arguments:

  • string: The value to parse.
  • radix: An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string.

We also know that map method expects a callback as an argument. The callback itself can accept 3 arguments:

  • the value of the element
  • the index of the element
  • and the array object being mapped

So what happens in the example above?

Long story short, because we didn't pass the radix number (base) to parseInt, and parseInt is the callback in map, the second argument of the callback in map being the index of each element in the array, the index is passed down to parseInt as its second argument and parseInt "thinks" it is the radix (base) number.

So parseInt being the callback in map, will do this for each element of the array:

parseInt('1', 0) 
parseInt('2', 1)
parseInt('10', 2)

Which will result in:

[1, NaN, 2]

For '1' in base 0, parseInt evaluates 0 as falsey and the effect is the same as not passing a radix argument and it defaults to 10 so it is like writing it parseInt('1', 10)

For '2' in base 1, it returns NaN, because radix must be an integer between 2 and 36.

For '10' in base 2, it evaluates to 2.

If you want to convert array string values to integer values you could do this:

['1', '2', '10'].map(elem=> parseInt(elem, 10))
//output [1, 2, 10]

I hope this makes sense.

Happy coding!

Top comments (3)

Collapse
 
ikemkrueger profile image
Ikem Krueger

On Stack Overflow I found this snippet:

['1', '2', '10'].map(Number)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mahesh262 profile image
Mahesh262

let sum = "123"
output will be 6 how to do

Collapse
 
ikemkrueger profile image
Ikem Krueger • Edited

Iterate over every character, parse them to int and add them all together.