← Back toFront-end Tips

Create a function that accepts a single parameter

Written byPhuoc Nguyen
Category
Tip
Tags
JavaScript
Created
15 Mar, 2021
Last updated
08 Sep, 2022
Contributors
dylankenneally
Quite often, we use the `map` function to transform each item of an array into a new one. However, it's common to see an issue if we don't pass the parameter to the mapper function.
For example, the following code converts each item of array into a number:
['1', '2', '3', '4', '5'].map((v) => parseInt(v));

// [1, 2, 3, 4, 5]
However, the result isn't correct if we shorten it as below:
['1', '2', '3', '4', '5'].map(parseInt);

// [1, NaN, NaN, NaN, NaN]
The issue is caused by the fact that the mapper function accepts three parameters which are the array item, index, and the array. Calling `.map(parseInt)` means that we pass the item index to `parseInt` as the second parameter. As a result, we will see `NaN`.
This leads to a requirement of building a function that accepts only the first parameter, and ignore the remaining parameters.
const unary = (fn) => (params) => fn(params);
The `unary` function creates a wrapper of a function, and ignores all parameters except the first one. With that function in our hand, we can pass the mapper to the `map` function like this:
['1', '2', '3', '4', '5'].map(unary(parseInt));

// [1, 2, 3, 4, 5]

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn