Ready-to-Use JavaScript Snippets

These snippets solve real problems that come up in web development repeatedly. Each one is dependency-free and works in any modern browser or Node.js environment.

1. Debounce a Function

Prevents a function from firing too rapidly — essential for search inputs and resize handlers.

function debounce(fn, delay = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

2. Deep Clone an Object

Create a true deep copy without relying on JSON hacks (which break functions and dates).

const deepClone = (obj) => structuredClone(obj);

Note: structuredClone is available in modern browsers and Node.js v17+.

3. Slugify a String

Convert any text into a URL-friendly slug.

const slugify = (str) =>
  str.toLowerCase().trim()
     .replace(/[^\w\s-]/g, '')
     .replace(/\s+/g, '-')
     .replace(/-+/g, '-');

4. Format a Date

Human-readable date formatting without a library.

const formatDate = (date, locale = 'en-US') =>
  new Intl.DateTimeFormat(locale, {
    year: 'numeric', month: 'long', day: 'numeric'
  }).format(new Date(date));

// formatDate('2024-01-15') → "January 15, 2024"

5. Capitalize First Letter of Each Word

const titleCase = (str) =>
  str.replace(/\b\w/g, (c) => c.toUpperCase());

6. Get Unique Array Values

const unique = (arr) => [...new Set(arr)];

7. Chunk an Array

Split an array into smaller arrays of a given size — useful for pagination.

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
    arr.slice(i * size, i * size + size));

8. Check if an Element is in Viewport

const isInViewport = (el) => {
  const rect = el.getBoundingClientRect();
  return rect.top >= 0 && rect.bottom <= window.innerHeight;
};

9. Throttle a Function

Like debounce, but fires at a maximum rate rather than waiting for a pause.

function throttle(fn, limit = 300) {
  let lastCall = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastCall >= limit) {
      lastCall = now;
      fn(...args);
    }
  };
}

10. Copy Text to Clipboard

const copyToClipboard = (text) =>
  navigator.clipboard.writeText(text);

11. Get a Random Integer in a Range

const randomInt = (min, max) =>
  Math.floor(Math.random() * (max - min + 1)) + min;

12. Flatten a Nested Object

const flattenObject = (obj, prefix = '') =>
  Object.entries(obj).reduce((acc, [key, val]) => {
    const newKey = prefix ? `${prefix}.${key}` : key;
    if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
      Object.assign(acc, flattenObject(val, newKey));
    } else {
      acc[newKey] = val;
    }
    return acc;
  }, {});

13. Parse URL Query Params

const getParams = (url = window.location.href) =>
  Object.fromEntries(new URL(url).searchParams);

14. Toggle a CSS Class

const toggleClass = (el, cls) => el.classList.toggle(cls);

15. Wait / Sleep in Async Functions

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// Usage:
await sleep(1000); // pause for 1 second

Tip: Build Your Own Utility Library

As you collect snippets like these, consider organizing them into a personal utils.js file. Over time this becomes a private toolkit tailored to the way you work — faster than reaching for a library every time.