DEV Community

Discussion on: Explain this Javascript expression just like I'm five

Collapse
 
katzy687 profile image
Natti Katz

take a list of strings that represent numbers and return a new list with all the strings converted to the numbers they represent, but they now have the data type of number

Collapse
 
mervinsv profile image
Mervin • Edited

if you execute this statement, the result will be [10, NaN, 2, 3]. Why?
But if you use parseFloat instead of parseInt, you will get the list of numbers.
I can't really explain why this is happening. But you can use this one as a replacement:

["10", "10", "10", "10"].map(function(x){ return parseInt(x); })
Collapse
 
katzy687 profile image
Natti Katz • Edited

whoa, you're right. Can someone explain what is happening?

I usually write map functions like this

["10", "10", "10", "10"].map(item => parseInt(item));

and that does indeed return [10, 10, 10, 10].

passing just parseInt as a callback.. how does it know what arguments to take?

Thread Thread
 
ozzyogkush profile image
Derek Rosenzweig

This answer on StackOverflow gives the correct reasoning: stackoverflow.com/a/262511/910328