I'm running the following in the Node.JS console:
> ["30", "31", "32"].map(x => parseInt(x))
[ 30, 31, 32 ]
> ["30", "31", "32"].map(parseInt)
[ 30, NaN, NaN ]
Why aren't these expressions identical? Is there a semantic difference in calling a function in point-free style as opposed to an anynomous function?
parseInt accepts two arguments: the numeric string and the base. Array#map provides the element and the index as the first two arguments to its callback, which makes some of the numbers unparseable (the main cause likely being that there are digits that are invalid for the specified base, such as having the digit 2 when parsing a string as binary), resulting in NaN. The Number function can be used instead to avoid this pitfall, as it ignores all arguments except the first.
["30", "31", "32"].map(Number)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With