Skip to content

Instantly share code, notes, and snippets.

@ardislu
Created September 3, 2024 08:49
Show Gist options
  • Save ardislu/80a959887d5a7daaca125a6a344ebd7c to your computer and use it in GitHub Desktop.
Save ardislu/80a959887d5a7daaca125a6a344ebd7c to your computer and use it in GitHub Desktop.

Beware unexpected overloading in JavaScript array functions

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 array map() 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment