3

I feel like I'm doing some noobish overlooking of things. Can anyone help me understand why the following doesn't work

["1.1", "2.2", "3.3"].map(parseInt);
//=> [1, NaN, NaN]

This works though ???

["1.1", "2.2", "3.3"].map(function(num) {
  return parseInt(num);
});
//=> [1, 2, 3]

This seems to work too

["1.1", "2.2", "3.3"].map(Number);
//=> [1.1, 2.2, 3.3]
1
  • Note ["1.1", "1.1", "1.1", "2.2", "3.3"].map(parseInt);[1, NaN, 1, 2, 3] Commented Jan 30, 2014 at 23:21

1 Answer 1

6

Array.prototype.map passes more than one arguments to the callback. In particular the second argument it passes is the index of the element being processed.

parseInt accepts more than one argument. In particular the second argument it accepts is the base of the numeric system you are converting from.

When the second element is processed you are calling parseInt("2.2", 1), and since 2 is not a valid digit in base 1 the result is NaN.

If you declare a "wrapper" callback around parseInt then these additional arguments are lost and everything seems to work correctly, although you should always pass the second argument to parseInt.

Sign up to request clarification or add additional context in comments.

5 Comments

Ah, I knew it was noobish overlooking! Thanks for the insight. So is there any harm in me using .map(Number) then?
@naomik: No, Number is fine.
@naomik .map(parseFloat) works too.
@naomik ["1.1", "2.2", "3.3"].map(Math.floor) may do what you were originally intending with parseInt.
Thanks, Matt. The float is an okay solution too. If I needed to force an int, Math.floor looks like a good function to use :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.