10 JavaScript Snippets Every Developer Should Keep in Their Clipboard Manager
Boost your productivity with these reusable snippets. Copy-paste ready for every dev.
π
βοΈ Gianluca
π§ 10 JavaScript Snippets Every Developer Should Keep in Their Clipboard Manager
As developers, we often rewrite the same utilities over and over. To boost productivity, hereβs a curated list of 10 high-value JavaScript snippets you can copy and paste directly into your next project. These cover everyday needs like 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.
function copyToClipboard(text) {
navigator.clipboard.writeText(text)
}
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).substring(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] = acc[val] || []
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)
}