DEV Community

Cover image for 5 Javascript Utility functions I love the most ❤️
Alvaro Saburido
Alvaro Saburido

Posted on

5 Javascript Utility functions I love the most ❤️

Despite all the "trendy" tweets complaining about Javascript being too difficult (most coming from non-users 😅), Javascript is a marvelous language that allows us to create amazing stuff on the web.

Sometimes we found ourselves doing the same cool stuff over and over again in our projects, it could be a function to format the response of an API, to format dates, to check the current browser used.

What do we do if we have a function we need to re-use across the same project? We create a utility function.

In this article, I want to share my top 5 favorite Javascript utility functions that I use constantly on my projects. As a warning ⚠️, I'm not including methods like map, reduce, filter because they are built-in on the standard and do not require any customization.

Second disclaimer ⚠️, this article is very opinionated, I'm not a Javascript Guru, this is based on my personal likes and some of them maybe have a better way to be done, if so, don't hesitate to comment on your opinion & improvements, constructive feedback is well received.

5. Slugify

Sometimes we need to programmatically format a blog post title like one of my previous posts Vite 2 - A speed comparison in Vue into a string at the end of the domain URL.

Screenshot 2021-08-19 at 10.40.32

This unique identifier string vite-2-a-speed-comparison-in-vue is what we call a Slug

As a standard, the slug formatting should be:

  • lowercase: to avoid casing issues.
  • use of -: spaces and multiple '-' should be replaced with single '-'.
  • trimmed: from the start of the text.

The function takes a string parameter (in case of using Javascript only, use .toString() to ensure that the parameter is converted to string), then we use toLowerCase() to remove any casings and take advantage of the power of Regex to ensure all the previous requirements listed are fulfilled.

4. Mock Async

This one is especially versatile, let's put ourselves in context.

There will be times you will not have access to the Rest API or the BE team is low on capacity and you need to move forward the Frontend part of a ticket beforehand. I know, it's not ideal, but this utility becomes handy to test async code (like an API call) and be able to easily integrate your code once BE work is done.

Async === Promises so we basically create a new Promise with a setTimeout that resolves or reject depending on a boolean parameter.

const fakeAPICall = (success, timeout, value) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (success) {
      } else {
        reject({ message: 'Error' });
    }, timeout);

async function loadPosts() {
   try {
      const { data } = await fakeAPICall(true, 2000, 

      return data.posts;

   }, catch(error) {
     // Do what you need to do
Enter fullscreen mode Exit fullscreen mode

Another perfect fit for this function is testing async behaviors in unit testing like error handling on a component.

3. Is utility functions

I might be cheating here so I apologize in advance because this one is not a single utility function but a bunch of them.

They're straightforward enough but yet so powerful on everyday code. You need to conditionally check if the parameter of a function is an Object or an Array? You got it isObject and isArray . Need to check if the browser is Safari (I hope you don't need to) you got isSafari.

You can also see the value on composing functions, on the gist example, isEmpty functions use isObject and isArray internally.

 2. Deep Clone

This one still makes me very nervous. I remember spending hours and hours on a good solution to copy a deeply nested object or array into a new one without referencing (to avoid mutations).

Javascript offers several Shallow Copy options like Object.assign, the problem with those is that even if it creates an exact copy of the original object, if any of the properties is itself an object or array, it will copy the reference to that object. Check this article to get a deeper understanding of the topic.

What this function does essentially, is recursively (remember we might have nested objects inside arrays inside nested objects, infinite possibilities) check if the value of a property is a simple value or more complex and iterate into all the keys internally.

The result is an exact copy of the original item without references.

That brings us to the number one, drumrolls please


 1. 🎉 snakeToCamel (🐍 to 🐫)

Frontend and Backend Developers we are indeed, very different creatures, but if there is anything that separates us the most is:

How we case our properties.

Jokes aside (there is a really funny article about it here), if you benchmark various business-significant APIS you will found out that by default, they use snake-case formatting in the JSON response instead of the beautiful and visually pleasant camelCase we use in the Frontend.

Let's take Github's user repositories response as an example. If you fetch mine you will get a response where repo info looks similar to this:

    "id": 337852842,
    "node_id": "MDEwOlJlcG9zaXRvcnkzMzc4NTI4NDI=",
    "name": "alvaro-dev-labs-",
    "full_name": "alvarosaburido/alvaro-dev-labs-",
    "private": false,
    "homepage": null,
    "size": 53,
    "stargazers_count": 0,
    "watchers_count": 0,
    "language": "JavaScript",
    "has_issues": true,
    "has_projects": true,
    "has_downloads": true,
    "has_wiki": true,
    "has_pages": false,
    "forks_count": 1,
    "mirror_url": null,
    "archived": false,
    "disabled": false,
    "open_issues_count": 1,
    "license": null,
    "forks": 1,
    "open_issues": 1,
    "watchers": 0,
    "default_branch": "main"

Enter fullscreen mode Exit fullscreen mode

So how we can format this to be able to use repo.fullName or repo.defaultBranch?

You could deconstruct it and assign a new variable with the camelCase, which would be very inefficient.

I prefer to deeply format objects using this pair of utilities:

BAM magic! (Not really, just recursion and regex) we can safely format the DTO and create our objects on the Frontend.

Screenshot 2021-08-19 at 14.54.14

It's... so..beautiful. 😭

Wrap up.

That's pretty much about it, if you reach here, thank you for reading I hope this article has helped you in some way.

If you have any comments, questions, or just what to say hi, let's meet in the comment section.

Happy Coding!

Discussion (0)