Rapid UI Development in Just 3 Days!

Starting at $100 for the first milestone of UI Development

Ensuring that your codebase is scalable, well-organized, and reusable

Integrate backend-as-a-service platforms like Appwrite and Supabase

Reusable components, custom hooks, services, and other React best practices

Consistent Code using ESLint and Prettier

Choose your stack: React.js, Next.js, Gatsby.js

Book A Free Call Now!

6 Most Useful JavaScript Utility Functions with Typescript

7 min read

Who does not love shortcuts and reusable things? Of course, everyone because it saves time and makes it easier to use them anywhere. While working on a Javascript project we often create a utils file that has lots of independent and utility functions that can be used in multiple places in a Javascript app.

So, in this article, we will begin with the most commonly used and essential functions in JavaScript projects using typescript and then move to the more complex functions in upcoming blogs.

What if you are not using typescript? Will these functions still be helpful? Yes, you only have to remove typescript types to use functions without it.

Function#1: Add Leading Zero in JavaScript with the Ternary Operator

addLeadingZero function will take a single parameter number and returns a string.

We are simply saying if a number is greater than 9, return the number but change it to string, otherwise add 0 before the number.

Since we are using template literals, so 0${number} will also be a string.

const addLeadingZero = (number: number): string => (number > 9 ? number.toString() : `0${number}`)
addLeadingZero(4) // 04
addLeadingZero(12) // 12

Use Cases of Javascript Leading Zero Function

  • We add zero before numbers, mostly in counters. For example, you can use it in a fitness app for step counts or exercise reps.

Function#2: Choose a Random Element from an Array in JavaScript

Sometimes we need to pick a random element from an array.

We are using Math.random() function for picking random element.

But Math.random() returns a number that's greater than or equal to 0 and less than 1.

Then we are multiplying it by array length.

Let's see what it returns assume the array length is 10

Math.random() * 10
=> 4.08190407024189

We are getting result in friction so to make it round we will use Math.floor()

As per MDN docs:

The Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.

Note

We are using Math.floor() to round down the value because we are using array.length that returns the array length, and array index starts with 0.

This is what it looks like now:

Math.floor(Math.random() * arr.length)
=> 6

Now we are getting a random number from 0 to array length - 1

Now we can access an array item by its index.

const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple']
// Using a generic array type, Array<elementType>
const pickRandomElement = (arr: Array<string>): string =>
arr[Math.floor(Math.random() * arr.length)]
console.log('result =>', pickRandomElement(colors)) // result => blue
choose random element from array javascript

Use Cases of Choose a Random Element from an Array

  • Let's say you are building a random quote application where you need to pick any random quote from the array.
  • You can also use it for the lucky draw, giveaways, and more.

Function#3: Choose a Random Element from the Array Range

This function is almost similar to the above function. The only difference is it picks a random element from the defined array indices. For example, choose items from index 2 to index 4. The result will be either blue, yellow, or pink.

const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple']
const pickElementFromRange = (arr: string[], start: number, end: number) => {
return arr[Math.floor(Math.random() * (end - start + 1)) + start]
}
const result = pickElementFromRange(colors, 2, 4)
console.log('result ==>', result) // result ==> yellow

It takes three arguments: array, start index, and end index. It returns either a string or a number. As we have colors in the array, it will return the string.

choose random element from array range javascript

Use Cases Of Choose a Random Element from the Array Range

  • You can use it to select an element from a portion of the array. For example, pick a random number after the first 10 and before the last 10 elements.

Function#4: Filter Array of Objects by Property Value

Story

Suppose you have a software company with different roles like frontend engineers, backend developers, and designers. The list of engineers is an array of objects. So if we want to filter out the engineers by title.

Let's say we want to filter all the UI Designers.

type EngineerType = {
name: string
title: string
}[]
const engineers: EngineerType = [
{ name: 'John Doe', title: 'Frontend Engineer' },
{ name: 'Michael', title: 'UI Designer' },
{ name: 'Sara Doe', title: 'Backend Engineer' },
{ name: 'Fahad', title: 'UI Designer' },
]
const filterByProperty = (arr: EngineerType) => arr.filter((item) => item.title === 'UI Designer')
const result = filterByProperty(engineers)
console.log('result =>', result)
// result => [
// { name: 'Michael', title: 'UI Designer' },
// { name: 'Fahad', title: 'UI Designer' }
// ]

You can add multiple conditions here, like title is "UI Designer" and experience is "senior".

item.title === 'UI Designer' && item.experience === 'senior'

Use cases of Filter Array of Objects by Property Value function

This function has many use cases and is widely used, wherever we have a list (array or array of objects) and we want to filter that list we can use this method.


Function#5: Check if Array is empty in Javascript

This function will take an array as a parameter and return a boolean.

First, we will check if the parameter is really an array, if it's an array, check if it has length if both conditions are satisfied, it means it is not empty return false, and wise versa.

const emptyArray = []
const nonEmptyArray = [1, 2, 'hello']
// Using a union type
const isEmptyArray = (arr: (string | number)[]): boolean =>
Array.isArray(arr) && !arr.length ? true : false
const result1 = isEmptyArray(emptyArray)
const result2 = isEmptyArray(nonEmptyArray)
console.log('empty array', result1) // true
console.log('!empty array', result2) // false

Use cases of if Array is empty in Javascript function

  • We use this function when we want to perform some method on an array, especially on higher-order functions like map, filter, reducer, etc, but before applying method, we want to see if array is empty or not, because our code can be break if the array has no data.
  • In case of an empty array we want to do something else, for example, showing loader or showing text that says "we have no data"

Function#6: Check if Object is empty

This function will take an object as a parameter and return a boolean. Object.keys() take object as an argument and return array of its keys.

const person = {
name: 'John',
}
Object.keys(person)
// result ['name', 'email']

Now we can check if a result has any length. If yes, means the object is not empty, and wise versa.

const objWithValues = {
name: 'John',
}
const emptyObj = {}
const isEmptyObject = (obj: {}): boolean => (Object.keys(obj).length === 0 ? true : false)
console.log('obj with values', isEmptyObject(objWithValues)) // false
console.log('empty obj', isEmptyObject(emptyObj)) // true

Use cases of if Object is empty function

  • After an API call, we get an object as a response. Before applying any method to it, we want to check whether it has data or not. We can use this method here.

I hope these methods will help you in your projects, feel free to use them in your projects, I will update this list from time to time.