What's the difference between these two?
['1', '2', '3'].map(n => parseInt(n)); // Function 1
['1', '2', '3'].map(parseInt); // Function 2
Let's see the output:
['1', '2', '3'].map(n => parseInt(n));
[1, 2, 3] // As expected
['1', '2', '3'].map(parseInt);
[1, NaN, NaN] // Surprise!
While at first glance function 2 appears to just be a simplification of function 1, Array.prototype.map()
actually passes up to three parameters to the callback function:
element
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The arraymap()
was called upon.
And since parseInt()
takes two parameters (string
and radix
), function 2 is actually passing the index of the array as the radix parameter.
In other words, function 2 is equal to:
['1', '2', '3'].map((n, i) => parseInt(n, i)); // Function 2 with explicit parameters
So be careful when refactoring the inline callback functions in your array functions! When in doubt it's probably best to keep them explicit.