As developers, we often rewrite the same utilities. Hereβs a curated list of 10 high-value JavaScript snippets you can paste into your next project: debouncing, throttling, string formatting, and array manipulation.
1. Debounce Function
Limits how often a function is executed. Useful for input, scroll, or resize events.
function debounce(fn, delay) {
let timeout
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => fn(...args), delay)
}
}
2. Throttle Function
Ensures a function is only called once every X milliseconds.
function throttle(fn, limit) {
let inThrottle
return (...args) => {
if (!inThrottle) {
fn(...args)
inThrottle = true
setTimeout(() => { inThrottle = false }, limit)
}
}
}
3. Deep Clone
Safely clones nested objects and arrays using JSON (works for most use cases).
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj))
}
4. Copy to Clipboard
Copy any text string directly to the clipboard.
async function copyToClipboard(text) {
try { await navigator.clipboard.writeText(text) } catch {}
}
5. Check if Object is Empty
Utility to validate if an object has no keys.
function isEmpty(obj) {
return Object.keys(obj).length === 0
}
6. Generate Random ID
Generate unique IDs (not UUIDs, but useful for UI components).
function randomID(length = 8) {
return Math.random().toString(36).slice(2, 2 + length)
}
7. Sleep / Delay in Async Functions
Pause execution inside an async function.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
8. Group Array by Property
Group an array of objects by a shared key.
function groupBy(arr, key) {
return arr.reduce((acc, obj) => {
const val = obj[key]
;(acc[val] ||= []).push(obj)
return acc
}, {})
}
9. Capitalize First Letter
Format strings by capitalizing the first character.
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
10. Clamp a Number Between Two Values
Ensure a number stays within bounds.
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max)
}
π Final Tip
Supercharge your workflow with a clipboard manager like Espanso, Clipy, or Raycast. Keeping snippets ready-to-go will save you hours every week.