DEV Community


Posted on • Updated on

3 Javascript utility functions to show you why they matter

Many developers, especially juniors and beginners push understanding js utility functions like map(), reduce() to the side not realising that once you get it you will start seeing ways to use them to improve your code everywhere.

What are JS utility functions?

A utility function is :

  • A standalone function ( it is not a member of any class and is in the global namespace )

  • Has no side effects ( It does not change any of it parameters or any global variable )

  • It output is directly dependent on it input.

Why and When Utility Functions?

As mentioned earlier, utility functions are highly reuseable to perform common tasks.

They simplify things by making it easier to refactor code and minimize it.

Utility functions are generic snippets that will make your code more efficient.

Utilizing utility function is a great way to remain consistent across your projects and when you want to modify the underlying functionality, you only need to modify it from one place.

Do something an X number of times

A prevalent task to do in javascript is to repeat something many times.
Using the times(_numberOfTimes_ , _function_) will do exactly that in a clean, practical way.

You can implement this functionality by using _. helper library.

Remove duplicates from an array

There are many utility functions for modifying arrays as you would expect which you can find on here
One useful one is removeDuplicates(array) it returns a new array with all the duplicates stripped away.

Find the difference of two arrays

Finds the repeating values in both arrays and return them in a string just by typing a simple one liner intersection(arr1,arr2, ...args)

Utility functions are a sea of information and it is very easy to get lost in it, so becareful and be wary of the bloat that you may unintentionally add with implementing all these libraries like lodash.

Personally, I recommend that you build your own lightweight utility functions library, adding only the ones you find extremely useful.

Top comments (0)