Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
1–10 of 163 posts
Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#2I much prefer languages like C#, C++ or TypeScript where the compiler warns me of such problems.
Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#3That's hilarious. Everybody loves the syntactic sugar that makes things easy, until the unexpected point where it makes things very hard.
Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#4Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#5Stuff like this is what drives me crazy when I work with dynamic languages like JS or PHP. I have seen a lot of code that looked perfectly fine but suffered from unexpected casts or defaults. I much prefer languages like C#, C++ or TypeScript where the compiler warns me of such problems.
Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#6This isn't strange or surprising. parseInt takes two arguments, the second one is the radix and map will call with three arguments, the value, the index and the whole array. You just have to know this and it might be different in other languages. [ ... ].map(x => ...) is the right way to do this.
Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#7Using directly like this a function with map() is just incorrect, the correct way to do it is:
['1', '7', '11'].map(x => parseInt(x))
edit I'm getting downvoted, it doesn't matter much but I don't understand it when the most upvoted comment seems to say more or less the same?Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#8Re: Why ['1', '7', '11'].map(parseInt) returns [1, NaN, 3] in JavaScript
#9This isn't strange or surprising. parseInt takes two arguments, the second one is the radix and map will call with three arguments, the value, the index and the whole array. You just have to know this and it might be different in other languages. [ ... ].map(x => ...) is the right way to do this.
Surprise! You need to know the basics of how your language works.