Posted by Kosal
JavaScript is a powerful language, but writing clean, reusable code is key to being efficient. That’s where utility functions come in - these small, handy functions help you solve common problems quickly and elegantly.
Below are 22 must-know JavaScript utility functions. Each one includes a detailed description and example output using console.log
for easy testing in your own environment.
Limits how often a function can run by delaying execution until a specified time has passed without another call. Ideal for resize, search, or scroll events.
const debounce = (fn, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
};
const logSearch = debounce(() => console.log("Searching..."), 300);
logSearch(); // Waits 300ms before logging
Randomizes the order of items in an array. Frequently used in quizzes, games, or data sampling.
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
console.log(shuffle([1, 2, 3, 4, 5])); // [3, 1, 5, 4, 2]
Simplifies a Date
object into a standard ISO format string, which is widely used in forms, databases, and APIs.
const formatDate = date => new Date(date).toISOString().split('T')[0];
console.log(formatDate(new Date())); // e.g., "2025-05-21"
Filters an array to only unique values, preserving order. Useful for cleaning datasets or preventing repeated actions.
const unique = arr => [...new Set(arr)];
console.log(unique([1, 2, 2, 3, 4, 4])); // [1, 2, 3, 4]
Returns a list of values that occur more than once. Handy for validation or finding errors in data.
const findDuplicates = arr => [...new Set(arr.filter((v, i, a) => a.indexOf(v) !== i))];
console.log(findDuplicates([1, 2, 2, 3, 4, 4, 5])); // [2, 4]
Reduces a deeply nested array into a single-level array. Essential when dealing with complex data structures or deeply nested form inputs.
const flatten = arr => arr.flat(Infinity);
console.log(flatten([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
Generates a whole number between a given minimum and maximum (inclusive). Perfect for things like random IDs, game mechanics, or sampling data.
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInt(1, 100)); // e.g., 42
Returns true if a year contains February 29. Can help with date validation or calendar logic.
const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
console.log(isLeapYear(2024)); // true
Returns items that exist in both arrays. Very useful for comparing permissions, tags, or selected filters.
const intersect = (a, b) => a.filter(x => b.includes(x));
console.log(intersect([1, 2, 3], [2, 3, 4])); // [2, 3]
Transforms a sentence into a URL-safe "slug" — lowercase, hyphen-separated, and clean of special characters.
const slugify = str => str.toLowerCase().trim().replace(/\s+/g, '-').replace(/[^\w\-]+/g, '');
console.log(slugify("JavaScript Utility Functions")); // "javascript-utility-functions"
Shortens text beyond a set length, adding an ellipsis (...
). Very useful for UI elements like cards, previews, or tables.
const truncate = (str, len) => str.length > len ? str.slice(0, len) + '...' : str;
console.log(truncate("This is a long description", 10)); // "This is a ..."
Checks if a given string is a valid email using a simple regular expression. Great for form validation.
const isEmail = str => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
console.log(isEmail("test@example.com")); // true
Verifies whether an object has no keys. Commonly used to guard against undefined or default states.
const isEmptyObject = obj => Object.keys(obj).length === 0;
console.log(isEmptyObject({})); // true
Extracts parameters from a URL and returns them as an object. Perfect for building filters or reading navigation state.
const getQueryParams = url => Object.fromEntries(new URL(url).searchParams.entries());
console.log(getQueryParams("https://example.com?name=alex&age=25")); // { name: 'alex', age: '25' }
Makes the first character uppercase. Helpful for formatting names or titles in UI.
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize("developer")); // "Developer"
Turns an object into a URL-encoded query string, useful when working with APIs or redirects.
const toQueryString = obj => new URLSearchParams(obj).toString();
console.log(toQueryString({ name: 'alex', age: 25 })); // "name=alex&age=25"
Cleans an array by removing false, null, 0, "", undefined, and NaN — useful for sanitizing form data.
const compact = arr => arr.filter(Boolean);
console.log(compact([0, 1, false, 2, '', 3])); // [1, 2, 3]
Counts how many times a specific value appears in an array. Useful for analytics or game scoring.
const countOccurrences = (arr, val) => arr.reduce((acc, el) => el === val ? acc + 1 : acc, 0);
console.log(countOccurrences([1, 2, 2, 3, 2, 4], 2)); // 3
Converts a date into a human-readable "time ago" format (like "3 minutes ago" or "2 days ago"). Great for chat timestamps or post metadata.
const timeAgo = date => {
const diff = (new Date() - new Date(date)) / 1000;
const units = [
['year', 31536000], ['month', 2592000],
['day', 86400], ['hour', 3600],
['minute', 60], ['second', 1]
];
for (let [unit, seconds] of units) {
const val = Math.floor(diff / seconds);
if (val >= 1) return `${val} ${unit}${val > 1 ? 's' : ''} ago`;
}
return 'just now';
};
console.log(timeAgo('2025-05-01')); // e.g., "20 days ago"
Returns true if a string or value is a valid number. Useful in forms or data validation.
const isNumeric = val => !isNaN(parseFloat(val)) && isFinite(val);
console.log(isNumeric("123.45")); // true
Creates a new object by extracting specific keys from a larger one. Great for API requests or selective updates.
const pick = (obj, keys) => keys.reduce((res, key) => {
if (key in obj) res[key] = obj[key];
return res;
}, {});
console.log(pick({ name: "Alex", age: 25, role: "admin" }, ["name", "role"])); // { name: "Alex", role: "admin" }
Formats byte values (e.g., file size) into KB, MB, GB, etc., for better UI readability.
const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
};
console.log(formatBytes(10240)); // "10 KB"
These utility functions cover a wide range of daily development needs — from arrays to strings, dates to objects. Adding them to your toolbox will not only save time but also make your codebase cleaner and easier to maintain.