← Back toFront-end tips

Create a function that accepts a single parameter

Written byPhuoc Nguyen
Created
15 Mar, 2021
Last updated
08 Sep, 2022
Category
Tip
Tags
JavaScript
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:
js
['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:
js
['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.
js
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:
js
['1', '2', '3', '4', '5'].map(unary(parseInt));

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

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

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