DEV Community

Cover image for 10 Useful JavaScript Utility Functions Every Developer Should Know
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

10 Useful JavaScript Utility Functions Every Developer Should Know

JavaScript is a versatile language, and having a set of reliable utility functions can significantly enhance development efficiency. These functions simplify common tasks, improve code readability, and reduce errors. Below, we explore ten essential JavaScript utility functions that every developer should have in their toolkit, complete with explanations and practical examples.


1.Deep Clone an Object

Creating a deep copy of an object ensures that nested objects or arrays are fully copied, preventing unintended mutations of the original data.


function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}


Enter fullscreen mode Exit fullscreen mode

Example:

const original = { a: 1, b: { c: 2 } };
const copy = deepClone(original);
copy.b.c = 99; // original remains unchanged

Enter fullscreen mode Exit fullscreen mode

2.Format Numbers with Commas

Formatting numbers for display, such as adding commas for thousands or fixing decimal places, enhances user experience.

function formatNumber(n) {
  return n.toLocaleString();
}

Enter fullscreen mode Exit fullscreen mode

Example:

formatNumber(1000000); // "1,000,000"

Enter fullscreen mode Exit fullscreen mode

3.Capitalize the First Letter

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Enter fullscreen mode Exit fullscreen mode

Example:

capitalize("hello world"); // "Hello world"

Enter fullscreen mode Exit fullscreen mode

4.Flatten an Array

function flattenArray(arr) {
  return arr.flat(Infinity);
}

Enter fullscreen mode Exit fullscreen mode

Example:

const log = debounce(() => console.log('Debounced!'), 500);
window.addEventListener('resize', log); // Logs only after 500ms of no resizing

Enter fullscreen mode Exit fullscreen mode

5.Debounce a Function

function debounce(fn, delay = 300) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
}

Enter fullscreen mode Exit fullscreen mode

Example:


window.addEventListener('resize', debounce(() => {
  console.log('Window resized!');
}, 500));


Enter fullscreen mode Exit fullscreen mode

6.Generate a Random Hex Color


function randomColor() {
  return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
}


Enter fullscreen mode Exit fullscreen mode

Example:


randomColor(); // "#a3e12f"

Enter fullscreen mode Exit fullscreen mode

7.Check If an Object is Empty


function isEmpty(obj) {
  return Object.keys(obj).length === 0;
}

Enter fullscreen mode Exit fullscreen mode

Example:


isEmpty({}); // true
isEmpty({ name: 'John' }); // false

Enter fullscreen mode Exit fullscreen mode

8.Convert Query String to Object


function parseQueryString(query) {
  return Object.fromEntries(new URLSearchParams(query));
}

Enter fullscreen mode Exit fullscreen mode

Example:
Converts ?name=John&age=30 into a usable object.

parseQueryString('?name=John&age=30'); // { name: "John", age: "30" }

Enter fullscreen mode Exit fullscreen mode

9.Copy Text to Clipboard

Splitting an array into smaller chunks is useful for pagination or batch processing.


async function copyToClipboard(text) {
  await navigator.clipboard.writeText(text);
}

Enter fullscreen mode Exit fullscreen mode

Example:
Enable “copybuttonsfor links, promo codes, etc.


copyToClipboard("Hello, world!");

Enter fullscreen mode Exit fullscreen mode

Works only on HTTPSand requires user interaction in modern browsers.


10.Generate a UUID (v4-style)


function generateUUID() {
  return crypto.randomUUID();
}

Enter fullscreen mode Exit fullscreen mode

Example:
Create unique IDs for form elements, DB records, or tokens.


generateUUID(); // "6fd9f51c-8df3-4a7b-a1f7-3c72ec518d1a"

Enter fullscreen mode Exit fullscreen mode

Native crypto.randomUUID() is supported in all modern browsers (2022+).


Bonus: Wrap These in a Utility Module

You can group all of these into a single reusable file:


// utils.js
export {
  deepClone,
  formatNumber,
  capitalize,
  flattenArray,
  debounce,
  randomColor,
  isEmpty,
  parseQueryString,
  copyToClipboard,
  generateUUID
};


Enter fullscreen mode Exit fullscreen mode

Then use them across your app:


import { debounce, formatNumber } from './utils.js';

Enter fullscreen mode Exit fullscreen mode

JavaScript utility functions are more than time-savers — they make your code cleaner, safer, and easier to maintain. Whether you're building a side project, an enterprise dashboard, or contributing to open source, mastering these functions gives you a real productivity boost.

Tip: Avoid rewriting the wheel on large projects. Use libraries like Lodash, Ramda, or Rambdawhen your app grows.

$150K MiniMax AI Agent Challenge — Build Smarter, Remix Bolder, Win Bigger!

Join the MiniMax AI Agent Challenge — Build your first AI Agent 🤖

Developers, innovators, and AI tinkerers, build your AI Agent and win $150,000 in cash. 💰

Read more →

Top comments (0)

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

👋 Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s day—leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay