49 Functions29 New11 Categories

JS Utility Functions

A curated library of ready-to-copy JavaScript utility functions — date formatting, array helpers, validation, async patterns, browser utilities, and more.

🔍

49 functions

formatDate(date, fmt)
Date

Formats a date using common display formats with ordinal suffixes.

Try it
16th Mar 26
getDateFromTimestamp(ts)
Date

Converts a Unix timestamp (seconds or ms) to a readable ISO date string.

Try it
2025-03-16 00:00:00
getDaysBetween(d1, d2)new
Date

Returns the number of days between two dates.

Try it
74 day(s) between 2026-01-01 and 2026-03-16
isToday(date)new
Date

Returns true if the given date is today.

Try it
✓ Yes, it's today
startOfDay(date)new
Date

Returns a new Date set to 00:00:00.000 of the given day.

Try it
2026-03-16T00:00:00.000Z
addDays(date, n)new
Date

Adds N days to a date and returns the new Date.

Try it
+7 days → 2026-03-23
timeAgo(date)
Time

Converts a date/timestamp into a relative human-readable string.

Try it
1h ago
formatTime(date, fmt)
Time

Formats time as 12h or 24h with optional seconds.

Try it
1:30 PM
truncate(str, len)
String

Truncates a string to a given length and appends ellipsis.

Try it
The quick brown fox ...
slugify(str)
String

Converts a string to a URL-friendly slug.

Try it
hello-world-this-is-a-test
capitalize(str)
String

Capitalizes the first letter of each word.

Try it
Hello World From Utils
generateId(len)
String

Generates a random alphanumeric ID of the given length.

Try it
zsh6crgqzcfr
formatCurrency(n, currency)
Number

Formats a number as a currency string using Intl.NumberFormat.

Try it
$12,499.50
formatBytes(bytes)
Number

Converts raw bytes to a human-readable size string (KB, MB, GB, TB).

Try it
1.5 MB
clamp(n, min, max)
Number

Clamps a number between min and max inclusive.

Try it
clamp(150, 0, 100) = 100
uniqueBy(arr, key)
Array

Removes duplicate objects from an array by a given key.

Try it
[{"id":1,"n":"A"},{"id":2,"n":"B"}]
groupBy(arr, key)
Array

Groups an array of objects by a given key.

Try it
{"a":[{"type":"a","v":1},{"type":"a","v":3}],"b":[{"type":"b","v":2}]}
chunk(arr, size)new
Array

Splits an array into chunks of the given size.

Try it
[[1,2,3],[4,5,6],[7]]
flatten(arr, depth)new
Array

Flattens a nested array to the specified depth.

Try it
[1,2,3,4,5,6]
sortBy(arr, key, dir)new
Array

Sorts an array of objects by a key, ascending or descending.

Try it
[{"n":"Cal","age":20},{"n":"Bob","age":25},{"n":"Ann","age":30}]
intersection(a, b)new
Array

Returns elements that exist in both arrays.

Try it
[3,4,5] (∩ with [3,4,5,6,7])
deepClone(obj)
Object

Creates a deep clone of an object (no reference sharing).

Try it
{"a":1,"b":{"c":2}}
omit(obj, keys)
Object

Returns a new object with specified keys removed.

Try it
{"id":1,"name":"John"}
debounce(fn, ms)
Object

Delays function execution until after a wait period.

Try it
debounce(fn, 300ms) → fn fires 300ms after last call
pick(obj, keys)new
Object

Returns a new object with only the specified keys.

Try it
{"id":1,"name":"John"}
flattenObject(obj)new
Object

Flattens a deeply nested object to dot-notation keys.

Try it
{"a.b.c":1,"d":2}
mergeDeep(target, source)new
Object

Deep-merges two objects; source values override target.

Try it
mergeDeep(input, {"b":{"y":99,"z":3},"c":4}) → {"a":1,"b":{"x":1,"y":99,"z":3},"c":4}
isEmail(str)
Validation

Validates whether a string is a properly formed email address.

Try it
✓ Valid email
isURL(str)
Validation

Validates whether a string is a valid absolute URL.

Try it
✓ Valid URL
isStrongPassword(str)
Validation

Checks for 8+ chars, uppercase, lowercase, number, and special character.

Try it
✓ Strong password
setStorage(key, value)new
Storage ✦

Saves any value to localStorage as JSON with an optional TTL (time-to-live).

Try it
localStorage unavailable in this context
getStorage(key)new
Storage ✦

Gets a value from localStorage and auto-removes it if expired.

Try it
localStorage unavailable
clearStorage(prefix)new
Storage ✦

Removes all localStorage keys that start with the given prefix.

Try it
localStorage unavailable
getURLParams(url)new
Browser ✦

Parses a URL query string into a plain key-value object.

Try it
{ "page": "2", "sort": "asc", "q": "hello" }
buildURL(base, params)new
Browser ✦

Builds a URL from a base string and a params object.

Try it
https://example.com?page=2&sort=asc&q=hello
setCookie(name, val, days)new
Browser ✦

Sets a browser cookie with an expiry date N days from now.

Try it
document.cookie = "session_id=abc123; expires=Mon, 23 Mar 2026 13:30:47 GMT; path=/"
getCookie(name)new
Browser ✦

Reads a cookie value by name from document.cookie.

Try it
Cookies unavailable
detectDevice()new
Browser ✦

Detects whether the current device is mobile, tablet, or desktop.

Try it
💻 Desktop
copyToClipboard(text)new
Browser ✦

Copies a string to the clipboard using the Clipboard API.

Try it
✓ Copied to clipboard: "Text to copy!"
getScrollPercent()new
Browser ✦

Returns how far the user has scrolled down the page as a 0–100% value.

Try it
sleep(ms)
Async ✦

Promise-based delay — use with await in async functions.

Try it
await sleep(1000) → pauses execution for 1000ms
retry(fn, attempts, delay)new
Async ✦

Retries an async function up to N times before throwing the final error.

Try it
retry(fn, 3, 500ms) → tries up to 3× with 500ms gap between each
withTimeout(promise, ms)new
Async ✦

Rejects a promise if it doesn't resolve within the specified ms.

Try it
withTimeout(fetchData(), 5000ms) → rejects if > 5000ms
asyncPool(limit, arr, fn)new
Async ✦

Runs async tasks over an array with a maximum concurrency limit.

Try it
asyncPool(3, items, fn) → max 3 concurrent tasks at a time
randomInt(min, max)new
Random ✦

Returns a random integer between min and max (both inclusive).

Try it
randomInt(1, 100) = 78
randomPick(arr)new
Random ✦

Picks and returns a random element from an array.

Try it
date
shuffle(arr)new
Random ✦

Shuffles an array in-place using the Fisher-Yates algorithm.

Try it
[4,2,5,7,6,3,8,1]
randomColor()new
Random ✦

Generates a random hex color code.

Try it
#0bec48
randomUUID()new
Random ✦

Generates a RFC 4122-compliant UUID v4.

Try it
e7e10321-3955-4d21-86c4-91e20bde6211

49 functions across 11 categories · Click any card to run live · Copy the code in one click