10 JavaScript Snippets Every Developer Should Keep in Their Clipboard Manager

Boost your productivity with these reusable snippets. Copy-paste ready for every dev.

πŸ“…

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.

Frequently Asked Questions

What is a debounce function in JavaScript?

A debounce function delays execution of a callback until a specified time has passed since the last call. It is commonly used on search inputs, scroll handlers, and resize events to prevent excessive function calls.

What is the difference between debounce and throttle in JavaScript?

Debounce waits for a quiet period before firing (ideal for search inputs), while throttle limits how often a function can fire regardless of how many times it is called (ideal for scroll or mouse-move events).

How do I deep clone an object in JavaScript without using external libraries?

The most reliable modern method is structuredClone(obj), available natively in Node.js 17+ and all modern browsers. For environments without it, JSON.parse(JSON.stringify(obj)) works for plain data, though it strips functions and undefined values.

How do I copy text to the clipboard in JavaScript?

Use the Clipboard API: await navigator.clipboard.writeText(text). This requires a secure context (HTTPS or localhost) and may prompt the user for permission in some browsers.