25 JavaScript One-Liners Every Developer Should Know

April 2026 · 6 min read · JavaScript

Compact, elegant JavaScript solutions that replace 10+ lines of code. Bookmark this page — you'll use these weekly.

Arrays

1. Remove Duplicates

const unique = [...new Set(array)];

2. Shuffle an Array

const shuffled = array.sort(() => Math.random() - 0.5);

3. Last Element

const last = array.at(-1);

4. Flatten Nested Arrays

const flat = array.flat(Infinity);

5. Group By Property

const grouped = Object.groupBy(array, item => item.category);

Objects

6. Deep Clone

const clone = structuredClone(original);

7. Merge Objects

const merged = { ...defaults, ...overrides };

8. Pick Properties

const pick = (obj, keys) => Object.fromEntries(keys.map(k => [k, obj[k]]));

9. Check Empty Object

const isEmpty = Object.keys(obj).length === 0;

Strings

10. Capitalize First Letter

const cap = str => str.charAt(0).toUpperCase() + str.slice(1);

11. Truncate with Ellipsis

const truncate = (str, n) => str.length > n ? str.slice(0, n) + '...' : str;

12. Slug from String

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

Numbers & Math

13. Random Integer in Range

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

14. Clamp a Value

const clamp = (n, min, max) => Math.min(Math.max(n, min), max);

15. Format Currency

const money = n => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(n);

DOM

16. Query All as Array

const $$ = sel => [...document.querySelectorAll(sel)];

17. Copy to Clipboard

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

18. Scroll to Top

const toTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });

19. Check if Element in Viewport

const inView = el => el.getBoundingClientRect().top < window.innerHeight;

Dates

20. Relative Time

const ago = date => new Intl.RelativeTimeFormat('en').format(
  Math.round((date - Date.now()) / 86400000), 'day'
);

21. Format Date

const fmt = date => new Intl.DateTimeFormat('en-US', { dateStyle: 'long' }).format(date);

Async

22. Sleep / Delay

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

23. Retry with Backoff

const retry = async (fn, n = 3) => { for (let i = 0; i < n; i++) try { return await fn() } catch(e) { if (i === n-1) throw e; await sleep(2**i * 1000) } };

Utility

24. Debounce

const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms) } };

25. UUID

const uuid = () => crypto.randomUUID();

⚡ 170+ production-ready templates

Each one uses clean, modern JavaScript like this. Zero dependencies, copy-paste ready.

Get the Bundle — $49

Want to test your regex patterns? Try our free regex tester. Need to format JSON? Use our JSON formatter.