Tricky use case of Array.prototype.map in JS

If you are familiar with functional programming, Array.prototype.map must be a function that you work with every day.

For me, map() is a powerful function, but there might be some tricky use case of it that you don't know about!

Let's walk through some basic knowledge

The map() method creates a new array from the calling array by applying a provided callback function once for each element of the calling array

Simple use cases

Giving this array

What can we do using map() function:

  • Getting new values from array
  • Extracting values from array of objects
  • Rendering list in React application

Tricky use case

It is common to pass the pre-defined callback function as map() argument like this:

But this habit may lead to unexpected behaviors with functions that take additional arguments.

Consider this case - we need to get all ids as numbers:

You might expect the result is [1, 2, 3, 4], but the actual result is [1, NaN, NaN, NaN]

We encountered this problem at Cốc Cốc recently, it took me a while to figure out, and here's the answer...

Usually, we use map() callback with 1 argument (the element being traversed), but Array.prototype.map passes 3 arguments:

  • the element
  • the index
  • the calling array (which we don't use most of the time)

And the callback in this case - parseInt is often used with 1 argument but it takes 2:

  • string: the value to parse
  • radix: [Optional]: an integer that represent the radix (the base in mathematical numeral systems) - usually, it's 10

For example:

And here you can see the source of confusion !

The third argument of map() is ignored by parseInt - but not the second one!

Hence, the iteration steps of map() look like this:

Solution

As you've known the source of the problem, the solution is not to pass all of the map()'s arguments to your callback if you're not sure how it works

  • Passing only the arguments that your callback needs

And that's what I know about Array.prototype.map function, feel free to share your use cases in the comment section

Happy coding!

Refs