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)); } Example: const original = { a: 1, b: { c: 2 } }; const copy = deepClone(original); copy.b.c = 99; // original remains unchanged 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(); } Example: formatNumber(1000000); // "1,000,000" 3.Capitalize the First Letter function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } Example: capitalize("hello world"); // "Hello world" 4.Flatten an Array function flattenArray(arr) { return arr.flat(Infinity); } Example: const log = debounce(() => console.log('Debounced!'), 500); window.addEventListener('resize', log); // Logs only after 500ms of no resizing 5.Debounce a Function function debounce(fn, delay = 300) { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => fn(...args), delay); }; } Example: window.addEventListener('resize', debounce(() => { console.log('Window resized!'); }, 500)); 6.Generate a Random Hex Color function randomColor() { return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`; } Example: randomColor(); // "#a3e12f" 7.Check If an Object is Empty function isEmpty(obj) { return Object.keys(obj).length === 0; } Example: isEmpty({}); // true isEmpty({ name: 'John' }); // false 8.Convert Query String to Object function parseQueryString(query) { return Object.fromEntries(new URLSearchParams(query)); } Example: Converts ?name=John&age=30 into a usable object. parseQueryString('?name=John&age=30'); // { name: "John", age: "30" } 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); } Example: Enable “copy” buttonsfor links, promo codes, etc. copyToClipboard("Hello, world!"); Works only on HTTPSand requires user interaction in modern browsers. 10.Generate a UUID (v4-style) function generateUUID() { return crypto.randomUUID(); } Example: Create unique IDs for form elements, DB records, or tokens. generateUUID(); // "6fd9f51c-8df3-4a7b-a1f7-3c72ec518d1a" 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 }; Then use them across your app: import { debounce, formatNumber } from './utils.js'; 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.

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));
}
Example:
const original = { a: 1, b: { c: 2 } };
const copy = deepClone(original);
copy.b.c = 99; // original remains unchanged
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();
}
Example:
formatNumber(1000000); // "1,000,000"
3.Capitalize the First Letter
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
Example:
capitalize("hello world"); // "Hello world"
4.Flatten an Array
function flattenArray(arr) {
return arr.flat(Infinity);
}
Example:
const log = debounce(() => console.log('Debounced!'), 500);
window.addEventListener('resize', log); // Logs only after 500ms of no resizing
5.Debounce a Function
function debounce(fn, delay = 300) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
Example:
window.addEventListener('resize', debounce(() => {
console.log('Window resized!');
}, 500));
6.Generate a Random Hex Color
function randomColor() {
return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
}
Example:
randomColor(); // "#a3e12f"
7.Check If an Object is Empty
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
Example:
isEmpty({}); // true
isEmpty({ name: 'John' }); // false
8.Convert Query String to Object
function parseQueryString(query) {
return Object.fromEntries(new URLSearchParams(query));
}
Example:
Converts ?name=John&age=30
into a usable object.
parseQueryString('?name=John&age=30'); // { name: "John", age: "30" }
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);
}
Example:
Enable “copy
” buttons
for links
, promo codes, etc.
copyToClipboard("Hello, world!");
Works only on HTTPS
and requires user interaction in modern browsers.
10.Generate a UUID (v4-style)
function generateUUID() {
return crypto.randomUUID();
}
Example:
Create unique IDs for form elements, DB records, or tokens.
generateUUID(); // "6fd9f51c-8df3-4a7b-a1f7-3c72ec518d1a"
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
};
Then use them across your app:
import { debounce, formatNumber } from './utils.js';
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 Rambda
when your app grows.