DEV Community

Cover image for If You Know These 30 JavaScript One-Liners, You’re Fast
Sukhpinder Singh
Sukhpinder Singh

Posted on

If You Know These 30 JavaScript One-Liners, You’re Fast

A very specific night (and a very silly bug)

2:13 a.m. in a quiet apartment. My laptop fan sounded like a small helicopter and the last of my jasmine tea had turned into something medicinal. I was stubbornly wrestling with a cookie helper. Twelve lines, three branches, one off-by-one.

Teammate (on Slack): “Ship it?”
Me: “…are we sure?”

That’s when I opened my scrappy snippets.md and started replacing noisy helpers with sharp, honest one-liners. Not golfed code—clear code. Since then, these 20 lines have paid rent in production.

Here’s the list, plus where each one helped, and the trade-offs I learned the hard way.


1) Get a cookie value (stop overbuilding)

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
Enter fullscreen mode Exit fullscreen mode

Where it helped: Login flakiness on staging; I needed to peek at _ga quickly.
Watch out: Won’t see HttpOnly cookies (that’s a good thing). Path/domain matter.


2) RGB → Hex (design → CSS handshake)

const rgbToHex = (r, g, b) => "#" + ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
Enter fullscreen mode Exit fullscreen mode

Story: Designer sent RGB, theme wanted hex. This bridged it during a UI polish sprint.
Guard: Validate 0–255. I’ve shipped rgbToHex(300, -2, 10) (facepalm).


3) Copy to clipboard (no hidden inputs)

const copyToClipboard = text => navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

Fix: I ditched the execCommand relic.
Gotcha: Needs https and user gesture; attach to a click or keydown.


4) Day of year (for streaks and cohorts)

const dayOfYear = d => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 86400000);
Enter fullscreen mode Exit fullscreen mode

Real use: A “learning streak” badge that computed day numbers.
TZ note: Normalize to UTC if the boundary matters.


5) Capitalize (because JS still won’t)

const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
Enter fullscreen mode Exit fullscreen mode

True story: I once typed Substring (C# muscle memory) in a JS file. Linter laughed at me.


6) Days between (no Moment, no drama)

const dayDif = (a, b) => Math.ceil(Math.abs(a - b) / 86400000);
Enter fullscreen mode Exit fullscreen mode

Use: “Remind me in N days” cards.
Caveat: Payroll/leave apps should use a real date lib—DST is a gremlin.


7) Clear all cookies (panic button)

document.cookie.split(';').forEach(c => document.cookie = c.replace(/^ +/,'')
  .replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
Enter fullscreen mode Exit fullscreen mode

When: Before a demo when auth state got weird.
Note: Cookies set on a different path/domain may survive.


8) Random hex (rapid prototyping)

const randomHex = () => `#${Math.floor(Math.random()*0xffffff).toString(16).padEnd(6,'0')}`;
Enter fullscreen mode Exit fullscreen mode

Fun: Temporary avatar colors in a “team picker.”
Accessibility: Not contrast-safe by default—never ship this to prod UIs without checks.


9) Unique array (goodbye 15-line loop)

const removeDuplicates = arr => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

Gotcha: Works on primitives. For objects, dedupe by key:

const uniqBy = (arr, key) => [...new Map(arr.map(x => [x[key], x])).values()];
Enter fullscreen mode Exit fullscreen mode

10) Query params (quick & dirty)

const getParameters = url =>
  JSON.parse('{"' + decodeURI(url.split("?")[1]).replace(/"/g,'\\"')
  .replace(/&/g,'","').replace(/=/g,'":"') + '"}');
Enter fullscreen mode Exit fullscreen mode

Confession: I used this mid-debug to unblock myself.
Long-term: Prefer new URL(url).searchParams.get('q')—clearer, safer.


11) Time from Date (hh:mm:ss)

const timeFromDate = d => d.toTimeString().slice(0, 8);
Enter fullscreen mode Exit fullscreen mode

When: Console output for job runtimes.
Internationalization: For UI, use Intl.DateTimeFormat.


12) Even check (small reads better)

const isEven = n => n % 2 === 0;
Enter fullscreen mode Exit fullscreen mode

Aside: I used to write !(n & 1) to feel clever. Then I started writing for humans.


13) Average (tiny analytics helper)

const average = (...xs) => xs.reduce((a,b)=>a+b,0) / xs.length;
Enter fullscreen mode Exit fullscreen mode

Guard: Empty input → NaN. I now wrap with xs.length ? … : 0.


14) Scroll to top (be kind: smooth)

const goToTop = () => window.scrollTo({ top: 0, left: 0, behavior: 'smooth' });
Enter fullscreen mode Exit fullscreen mode

Respect: Users with reduced motion—feature-detect or let CSS media queries handle it.


15) Reverse string (classic chain)

const reverse = s => s.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

Unicode footnote: Grapheme clusters (emoji/accents) need a lib or Intl.Segmenter.


16) Array not empty (guard clause)

const isNotEmpty = a => Array.isArray(a) && a.length > 0;
Enter fullscreen mode Exit fullscreen mode

Why I keep it: Reads like English and kills a whole if-ladder.


17) Selected text (handy in editors)

const getSelectedText = () => window.getSelection().toString();
Enter fullscreen mode Exit fullscreen mode

Shadow DOM: You may need selection from the right root; know your host.


18) Shuffle (fun, but biased)

const shuffleArray = a => a.sort(() => 0.5 - Math.random());
Enter fullscreen mode Exit fullscreen mode

Honesty: Great for a quick demo. For fairness, I use Fisher–Yates:

const fyShuffle = a => { for (let i=a.length-1;i>0;i--){ const j=Math.floor(Math.random()*(i+1)); [a[i],a[j]]=[a[j],a[i]];} return a; };
Enter fullscreen mode Exit fullscreen mode

19) Detect dark mode (respect the user)

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
Enter fullscreen mode Exit fullscreen mode

Pattern: Toggle a data-theme attribute and let CSS carry the weight.



20) Debounce (collapse rapid calls)

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

Use: search-as-you-type, resize handlers.
Note: Last call wins.


21) Throttle (limit call rate)

const throttle = (fn, ms) => { let p = 0; return (...a) => { const n = Date.now(); if (n - p > ms) { p = n; fn(...a); } }; };
Enter fullscreen mode Exit fullscreen mode

Use: scroll listeners, pointer move.
Note: Drops calls within the window.


22) Clamp (keep a number in range)

const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
Enter fullscreen mode Exit fullscreen mode

Use: slider values, pagination bounds.


23) Chunk an array

const chunk = (arr, size) => arr.reduce((r, _, i) => (i % size ? r[r.length-1].push(arr[i]) : r.push([arr[i]]), r), []);
Enter fullscreen mode Exit fullscreen mode

Use: grid rows, batched requests.


24) Deep-flatten any nested array

const flat = arr => arr.flat(Infinity);
Enter fullscreen mode Exit fullscreen mode

Use: merging API results.
Note: Requires modern runtimes (widely supported).


25) Range generator (length n, optional start)

const range = (n, start = 0) => Array.from({ length: n }, (_, i) => i + start);
Enter fullscreen mode Exit fullscreen mode

Use: page numbers, skeleton loaders.


26) Sleep / delay as a Promise

const sleep = ms => new Promise(r => setTimeout(r, ms));
Enter fullscreen mode Exit fullscreen mode

Use: UI pauses, backoff between retries.


27) Fetch JSON (tiny helper)

const getJSON = (url, opts) => fetch(url, opts).then(r => r.json());
Enter fullscreen mode Exit fullscreen mode

Use: quick prototypes.
Note: No error handling—wrap if you need robustness.


28) Group by key

const groupBy = (arr, key) => arr.reduce((m, x) => ((m[x[key]] = m[x[key]] || []).push(x), m), {});
Enter fullscreen mode Exit fullscreen mode

Use: table sections, charts datasets.


29) Safe deep get with default

const get = (obj, path, dflt) => path.split('.').reduce((v, k) => v?.[k], obj) ?? dflt;
Enter fullscreen mode Exit fullscreen mode

Use: reading optional API fields without try/catch.


30) The mindset: compress only when it clarifies

There’s a difference between clever and considerate. I used to minify everything I could; now I compress only when the next reader—maybe tired, maybe rushing—will understand it faster.

Quotable: “Great code isn’t shorter. It’s clearer—and usually that means fewer moving parts.”


Tiny sketch: how the “quick params” trick works

[ URL ] -> [ split "?" ] -> [ decode ] -> [ replace &/= ] -> [ JSON.parse ] -> { params }
Enter fullscreen mode Exit fullscreen mode

Alt text: A simple linear flow showing a raw URL string transformed into a params object via split/replace/parse.


Three real postmortems (because production is humbling)

#1532 Clipboard flaked in staging

  • Symptom: Worked locally, failed behind reverse proxy.
  • Root cause: Missing secure context; no user gesture.
  • Fix: Wire to a click; ensure https in all envs.
  • Commit: 9ad1bf7 (the “toast added” one).

#1619 Streak counter off by one

  • Symptom: Users in GMT+9 saw tomorrow’s day number.
  • Fix: Normalize to UTC midnight; compute in back end.
  • Lesson: Time zones don’t care about your sprint goals.

#1674 Duplicate labels in chart

  • Symptom: Two bars with the same tag after a transform.
  • Fix: labels = [...new Set(labels)] pre-render.
  • Bonus: Added uniqBy for objects (see #9).

Skimmable checklists (paste into your notes)

Reach for a one-liner when…

  • The name reads like a sentence (isNotEmpty, timeFromDate).
  • It replaces boilerplate without hiding intent.
  • You’ve tested edge cases (TZ, permissions, Unicode).

Don’t one-line when…

  • Security or crypto logic lives there.
  • Accessibility depends on it (contrast, motion).
  • You need mathematically fair randomness (use Fisher–Yates).

How I keep these ready (small habit, big payoff)

  • I keep a snippets.md in the repo with headings and trade-offs.
  • I save tiny gists for the ones I reuse across projects.
  • I leave a one-line comment above each snippet: what it does + when not to use it.
  • I prune. If a snippet causes more questions than answers, it’s gone.

Recap (7 takeaways)

  • One-liners are tools, not trophies.
  • Prefer clarity > cleverness.
  • Normalize time. Respect motion preferences. Guard inputs.
  • Set, Map, URL, Intl—lean on the platform first.
  • Prototype fast, then refactor the “quick & dirty.”
  • Document trade-offs right above the snippet.
  • Share your snippet file—teams improve it together.

Let’s make this a living toolbox

What’s the one-liner you reach for without thinking?
Drop it in the comments—I’ll collect the best ones and credit you in a follow-up.

Follow if you like practical, production-tested posts with fewer buzzwords and more “here’s what actually shipped.”


Top comments (0)