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:
- parseInt function parses a string and returns an integer.
- 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)
On Stack Overflow I found this snippet:
let sum = "123"
output will be 6 how to do
Iterate over every character, parse them to int and add them all together.