0

I was stumbling on http://lihaoyi.github.io/hands-on-scala-js/ where I found below :

javascript> ["10", "10", "10", "10"].map(parseInt)
[10, NaN, 2, 3] // WTF


scala> List("10", "10", "10", "10").map(parseInt)
List(10, 10, 10, 10) // Yay!

Below are details of map() from : http://www.tutorialspoint.com/javascript/array_map.htm

Javascript array map() method creates a new array with the results of calling a provided function on every element in this array.

No explanation given on former link mentioned. Couldn't understand whats going on with 2nd param? Why is parseInt returning NaN?

Snehal Masne
  • 3,403
  • 3
  • 31
  • 51
  • 1
    Notice, that you're passing an index as `radix` parameter in `parseInt`. – Teemu Sep 04 '15 at 14:30
  • 1
    I agree. The actual proper code is `["10", "10", "10", "10"].map(function(bla) { return parseInt(bla,10)})` - the code in the Scala example is BS – mplungjan Sep 04 '15 at 14:31

1 Answers1

1

parseInt accepts 2 parameters, 1st - string, 2nd- radix. Details here

map passing 3 parameters to callback, value, key and whole arry. Details here

So you're seeing execution of code like this

parseInt("10", 0);
parseInt("10", 1);
parseInt("10", 2);
parseInt("10", 3);

and it works correctly :)

To fix, you can do something like:

["10", "10", "10", "10"].map(function (value) {
    return parseInt(value);
});
//[10, 10, 10, 10]
Andrey
  • 4,020
  • 21
  • 35