Tips November 3, 2025 6 mins read

50 JavaScript Snippets You’ll Reuse in 2025

Whether you’re optimizing a SaaS dashboard, automating workflows, or cleaning up messy code — these 50 JavaScript snippets will make your life easier. They follow modern ES2025 standards, require zero dependencies, and are designed for real-world reusability.

Whether you’re optimizing a SaaS dashboard, automating workflows, or cleaning up messy code — these 50 JavaScript snippets will make your life easier.
They follow modern ES2025 standards, require zero dependencies, and are designed for real-world reusability.

Arrays / Objects

Work smarter with data. Handle arrays, objects, and collections with clean, reusable helpers.

// 1. Remove duplicates
const unique = arr => [...new Set(arr)];

// 2. Deep clone object
const clone = obj => structuredClone(obj);

// 3. Merge objects
const merged = { ...obj1, ...obj2 };

// 4. Sort by key
const sortBy = (arr, key) => arr.sort((a, b) => a[key] - b[key]);

// 5. Group by property
const groupBy = (arr, key) =>
  arr.reduce((acc, obj) => ((acc[obj[key]] ??= []).push(obj), acc), {});

// 6. Flatten array
const flatten = arr => arr.flat(Infinity);

// 7. Count occurrences
const count = arr =>
  arr.reduce((acc, v) => ((acc[v] = (acc[v] || 0) + 1), acc), {});

// 8. Get random element
const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];

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

// 10. Filter truthy values
const clean = arr => arr.filter(Boolean);

Effortless transformations for APIs, dashboards, and analytics pipelines.

Dates / Intl

Handle time zones, localization, and formatting the smart way.

// 11. Format date
const formatDate = date =>
  new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' }).format(date);

// 12. Relative time
const fromNow = date => {
  const diff = (Date.now() - date) / 1000;
  const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
  if (diff < 60) return rtf.format(-Math.round(diff), 'second');
  if (diff < 3600) return rtf.format(-Math.round(diff / 60), 'minute');
  if (diff < 86400) return rtf.format(-Math.round(diff / 3600), 'hour');
  return rtf.format(-Math.round(diff / 86400), 'day');
};

// 13. Add days
const addDays = (date, days) =>
  new Date(date.setDate(date.getDate() + days));

// 14. Start of day
const startOfDay = date => new Date(date.setHours(0, 0, 0, 0));

// 15. Days between
const daysBetween = (a, b) =>
  Math.round((b - a) / (1000 * 60 * 60 * 24));

// 16. ISO to local
const toLocal = iso => new Date(iso).toLocaleString();

// 17. Format currency
const formatCurrency = (n, c = 'USD') =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: c }).format(n);

// 18. Format percent
const formatPercent = n =>
  new Intl.NumberFormat('en-US', { style: 'percent' }).format(n);

// 19. Short month name
const shortMonth = d => new Date(d).toLocaleString('en', { month: 'short' });

// 20. Weekday name
const weekday = d => new Date(d).toLocaleString('en', { weekday: 'long' });

Built on Intl, these snippets ensure your app speaks everyone’s language.

Async / Fetch

Clean async patterns for APIs, retries, and performance-safe waits.

// 21. Fetch with timeout
const fetchWithTimeout = (url, ms = 5000) =>
  Promise.race([
    fetch(url),
    new Promise((_, reject) => setTimeout(() => reject('Timeout'), ms))
  ]);

// 22. Retry async call
const retry = async (fn, retries = 3) => {
  for (let i = 0; i < retries; i++) try { return await fn(); } catch {}
  throw new Error('Failed after retries');
};

// 23. Wait utility
const wait = ms => new Promise(res => setTimeout(res, ms));

// 24. Parallel fetches
const fetchAll = urls => Promise.all(urls.map(u => fetch(u).then(r => r.json())));

// 25. Timeout wrapper
const timeout = (promise, ms) =>
  Promise.race([
    promise,
    new Promise((_, reject) => setTimeout(() => reject('Timeout!'), ms))
  ]);

// 26. Safe JSON parse
const safeJSON = str => { try { return JSON.parse(str); } catch { return null; } };

// 27. Sleep between loops
const asyncForEach = async (arr, cb) => {
  for (const item of arr) await cb(item);
};

// 28. Limit concurrent requests
const limitedFetch = async (urls, limit = 3) => {
  const result = [];
  while (urls.length) {
    const chunk = urls.splice(0, limit);
    const res = await Promise.all(chunk.map(u => fetch(u)));
    result.push(...res);
  }
  return result;
};

// 29. Async map
const asyncMap = async (arr, fn) => Promise.all(arr.map(fn));

// 30. Fetch JSON helper
const getJSON = async url => (await fetch(url)).json();

Ready-to-use async tools — efficient and reliable.

DOM Utilities

Quick DOM helpers that eliminate repetitive tasks.

// 31. Toggle class
const toggle = (el, cls) => el.classList.toggle(cls);

// 32. Smooth scroll
const scrollToEl = id => document.querySelector(id)?.scrollIntoView({ behavior: 'smooth' });

// 33. Copy text
const copy = text => navigator.clipboard.writeText(text);

// 34. Detect visibility
const isVisible = el => el.getBoundingClientRect().top < window.innerHeight;

// 35. Debounce
const debounce = (fn, delay) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
};

// 36. Throttle
const throttle = (fn, limit) => {
  let waiting = false;
  return (...args) => {
    if (!waiting) {
      fn(...args);
      waiting = true;
      setTimeout(() => (waiting = false), limit);
    }
  };
};

// 37. Element exists
const exists = sel => document.querySelector(sel) !== null;

// 38. Get form data
const formData = form => Object.fromEntries(new FormData(form));

// 39. Create element
const create = (tag, attrs = {}) =>
  Object.assign(document.createElement(tag), attrs);

// 40. Load script dynamically
const loadScript = src =>
  new Promise(res => {
    const s = document.createElement('script');
    s.src = src;
    s.onload = res;
    document.head.append(s);
  });

Perfect for UI tweaks, forms, and lightweight apps.

URL & Query

Manipulate and analyze URLs with native APIs.

// 41. Get query param
const getParam = key => new URLSearchParams(location.search).get(key);

// 42. Set query param
const setParam = (key, value) => {
  const url = new URL(location);
  url.searchParams.set(key, value);
  history.replaceState({}, '', url);
};

// 43. Delete param
const delParam = key => {
  const url = new URL(location);
  url.searchParams.delete(key);
  history.replaceState({}, '', url);
};

// 44. Parse URL parts
const parseUrl = url => new URL(url);

// 45. Build query string
const toQuery = obj => '?' + new URLSearchParams(obj).toString();

// 46. Get all params as object
const getParams = () =>
  Object.fromEntries(new URLSearchParams(location.search).entries());

// 47. Join URL segments
const joinUrl = (...parts) =>
  parts.map(p => p.replace(/(^\/+|\/+$)/g, '')).join('/');

// 48. Validate URL
const isValidUrl = str => {
  try { new URL(str); return true; } catch { return false; }
};

// 49. Change hash
const setHash = hash => (location.hash = hash);

// 50. Reload without cache
const reloadClean = () => location.reload(true);

Simple, effective, and built into the browser.

Performance Tips

A few micro-optimizations that improve your code’s runtime efficiency.

// Measure function time
const measure = fn => {
  const start = performance.now();
  fn();
  console.log(`${fn.name} took ${performance.now() - start}ms`);
};

// Memoize result
const memoize = fn => {
  const cache = new Map();
  return arg => cache.has(arg) ? cache.get(arg) : cache.set(arg, fn(arg)).get(arg);
};

Use them to keep your frontend snappy and responsive.

Summary

These 50 JavaScript snippets for 2025 are battle-tested, concise, and built to last.
Save them, share them, and reuse them in your next project — whether it’s a Chrome extension, a Filament dashboard, or a SaaS platform.

David Green

David Green