Half the “JavaScript one-liners” floating around social media are from 2018. Some still work fine. Others have been replaced by built-in methods that didn’t exist back then, and a few were quietly buggy all along.
So we rebuilt the list. These are 20 one-liners we ran in Node.js 24, with the actual output written under each. Where a method is new enough that an older Node install or browser might not have it, we say so.
One rule we kept: if a one-liner was clever but unreadable, it didn’t make the cut.
JavaScript array methods
1. Remove duplicates
[...new Set([3, 1, 3, 2, 1])]
// [3, 1, 2]
A Set keeps the first time it sees each value, so the original order survives. It compares objects by reference, though, so two identical-looking objects both stay.
For arrays of objects, dedupe by a key instead. A Map keyed on the ID does it:
const users = [
{ id: 1, name: "Ana" },
{ id: 2, name: "Ben" },
{ id: 1, name: "Ana (updated)" },
];
[...new Map(users.map((u) => [u.id, u])).values()]
// [{ id: 1, name: "Ana (updated)" }, { id: 2, name: "Ben" }]
Notice which Ana survived. The Map keeps the first position but the last value, so you get the newest copy. A plain new Set(users) kept all 3 objects when we ran it.
2. Get the last item
[10, 20, 30].at(-1)
// 30
Cleaner than arr[arr.length - 1]. Negative numbers count from the end.
3. Sum an array
[4, 8, 15].reduce((sum, n) => sum + n, 0)
// 27
Always pass that 0 at the end. Without it, reduce() on an empty array throws a TypeError.
4. Build a range
Array.from({ length: 5 }, (_, i) => i * 2)
// [0, 2, 4, 6, 8]
5. Split into chunks
const chunk = (arr, n) =>
Array.from({ length: Math.ceil(arr.length / n) }, (_, i) => arr.slice(i * n, i * n + n));
chunk([1, 2, 3, 4, 5, 6, 7], 3)
// [[1, 2, 3], [4, 5, 6], [7]]
Technically two lines here for width. Useful for pagination or batching API calls.
6. Drop empty values
[0, "a", "", null, 5, undefined, NaN].filter(Boolean)
// ["a", 5]
Careful: this removes 0 too. If zero is a real value in your data, filter on x != null instead.
7. Count how often each value appears
const count = (arr) => arr.reduce((acc, x) => ((acc[x] = (acc[x] ?? 0) + 1), acc), {});
count(["js", "py", "js", "go", "js"])
// { js: 3, py: 1, go: 1 }
The comma inside the parentheses returns acc after the update. It’s compact, but if your team finds it cryptic, a plain for...of loop is fine.
8. Group objects with Object.groupBy()
const people = [
{ name: "Zoe", team: "red" },
{ name: "Adam", team: "blue" },
{ name: "Mia", team: "red" },
];
Object.groupBy(people, (p) => p.team)
// { red: [Zoe, Mia objects], blue: [Adam object] }
This used to be a reduce() or a Lodash import. MDN lists Object.groupBy() as supported from Node 21. One oddity: the result has a null prototype, so methods like result.hasOwnProperty() don’t exist on it. We checked: Object.getPrototypeOf() on the result returns null.
9. Sort without changing the original
const nums = [10, 9, 1];
const sorted = nums.toSorted((a, b) => a - b);
// sorted: [1, 9, 10]
// nums: [10, 9, 1] (untouched)
toSorted() returns a new array. That matters in React state and anywhere else you shouldn’t mutate data in place.
It has three siblings that follow the same rule. With const a = [3, 1, 2], we got a.toReversed() as [2, 1, 3], a.with(0, 9) as [9, 1, 2] and a.toSpliced(1, 1) as [3, 2], and a itself was still [3, 1, 2] afterwards. Same Node 20+ requirement.
10. Find the last match
[3, 8, 2, 9, 4].findLast((n) => n > 5)
// 9
11. Items two lists share
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log([...a.intersection(b)]); // [2, 3]
console.log([...a.difference(b)]); // [1]
The new Set methods (intersection, union, difference and friends) arrived in Node 22. On older runtimes, arr1.filter(x => set2.has(x)) does the same job.
Notice the semicolons. Our first draft of this snippet had two lines that both started with [, and with no semicolon between them JavaScript glued them into one expression and threw a SyntaxError. If you skip semicolons in your style, that’s the one case to watch.

Strings, numbers and dates
12. Capitalize the first letter
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
capitalize("hello world")
// "Hello world"
We use charAt(0) instead of s[0] so an empty string returns "" rather than crashing on undefined.toUpperCase().
13. Random integer in a range
const randInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randInt(1, 6) // 1 to 6, both ends included
We rolled it 10,000 times and got values from 1 to 6, nothing outside. Not for passwords or tokens, though. Use crypto.getRandomValues() for anything security-related.
14. Format money properly
new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(1234.5)
// "$1,234.50"
Swap the locale and currency code and you get the right symbol and separators for that country, without string hacks.
Small habit worth having: build the formatter once and reuse it, rather than creating a new Intl.NumberFormat inside a loop. The options live in one place, and every price on the page is guaranteed to look the same.
15. “Yesterday”, “in 3 weeks”
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
rtf.format(-1, "day") // "yesterday"
rtf.format(3, "week") // "in 3 weeks"
16. Days between two dates
const daysBetween = (d1, d2) => Math.round((new Date(d2) - new Date(d1)) / 86_400_000);
daysBetween("2026-01-01", "2026-11-10")
// 313
Date-only strings like "2026-01-01" are parsed as UTC, which keeps daylight-saving shifts out of the answer. Math.round covers the rest. And 86_400_000 is just 86400000 with digit separators, easier to read at a glance.
Modern JavaScript tricks for objects and async
17. Safe deep access with a fallback
const user = { profile: null };
user.profile?.address?.city ?? "Unknown"
// "Unknown"
?? only falls back on null or undefined. The older || also replaces 0 and empty strings, which is a common source of bugs in forms.
18. Transform every value in an object
const prices = { apple: 1.2, bread: 2.5 };
Object.fromEntries(Object.entries(prices).map(([k, v]) => [k, v * 2]))
// { apple: 2.4, bread: 5 }
19. Real deep copy
const orig = { when: new Date("2026-01-01"), tags: ["a"] };
const copy = structuredClone(orig);
copy.tags.push("b");
// orig.tags is still ["a"], copy.when is still a Date
The old JSON.parse(JSON.stringify(obj)) trick turns dates into strings and drops undefined. structuredClone() keeps dates, maps and sets intact. It can’t copy functions, though, and throws if it meets one.
20. sleep()
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await sleep(200); // pauses this async function for ~200 ms
Good for retry loops and polite pauses between API calls. It doesn’t block the rest of your program, only the function that awaits it.
The classic mistake is calling it inside forEach. We tried [1, 2, 3].forEach(async () => { await sleep(300); }) and forEach returned after 0 ms, because it doesn’t wait for async callbacks. The same loop written as for (const n of [1, 2, 3]) { await sleep(300); } took close to a second, three pauses one after another. If the order or the delay matters, use for...of. We cover this one and nine other traps in JavaScript async/await mistakes and how to fix them.
A real example: cleaning up API data
These tricks are most useful in combination. Say an API sends you orders with a duplicate in it, and you need a quick summary by status:
const orders = [
{ id: 101, status: "paid", total: 40 },
{ id: 102, status: "pending", total: 15.5 },
{ id: 101, status: "paid", total: 40 },
{ id: 103, status: "paid", total: 22.25 },
];
const unique = [...new Map(orders.map((o) => [o.id, o])).values()];
const byStatus = Object.groupBy(unique, (o) => o.status);
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
for (const [status, list] of Object.entries(byStatus)) {
const sum = list.reduce((acc, o) => acc + o.total, 0);
console.log(`${status}: ${list.length} order(s), ${usd.format(sum)}`);
}
// paid: 2 order(s), $62.25
// pending: 1 order(s), $15.50
That’s the dedupe trick, Object.groupBy(), reduce() with a starting value and a reused formatter, all in about ten lines. Order 101 appeared twice in the input and was counted once. We ran it in Node 24 and the output above is what it printed.
Which Node.js version or browser do you need?
Node 22 or newer runs every snippet here. That lines up nicely with support: the Node.js releases page lists 18 and 20 as end-of-life, with 22 and 24 as the LTS lines. If a server or CI image is still on Node 20, tricks 8 and 11 will fail there, and upgrading is the real fix.
In browsers, the newest pieces are the Set methods, which MDN marks as Baseline 2024, newly available since June 2024. They work in current Chrome, Edge, Firefox and Safari, but a phone that hasn’t updated in a couple of years may not have them. For a public site, keep the filter() fallback or check MDN’s table first.
The catch: the most famous one-liner of all is broken. [10, 9, 1].sort() returns [1, 10, 9], because without a compare function JavaScript sorts numbers as strings. We ran it to be sure. It also mutates the original array. Pass (a, b) => a - b every time, or use toSorted() from trick 9. The same goes for the popular arr.sort(() => Math.random() - 0.5) “shuffle”: it’s biased. Use a Fisher-Yates loop if fairness matters.
Which JavaScript one-liners to use every day
The big shift since the old lists went viral is that JavaScript now has proper built-ins for things people used to import Lodash for: grouping, deep cloning, set math, non-mutating sorts. If your project targets current browsers or Node 22 and up, you can drop a few dependencies.
If you ship to older environments (some corporate machines, older Safari on iPads, serverless runtimes pinned to Node 18), check MDN’s compatibility table before using tricks 8, 9 and 11. A transpiler like Babel won’t polyfill methods unless you set that up separately.
Our pick for daily use: ?. with ??, structuredClone(), and Intl.NumberFormat. They fix real bugs, not just save keystrokes.
Also on the site: 15 Python tricks for beginners, all run on Python 3.12. And if you lean on an AI assistant for this kind of refactor, our AI prompts for coding include one that asks for “modern built-ins only, no new dependencies”.
Next: styling instead of scripting? See modern CSS tricks that replace old JavaScript hacks. Pulling that data out of a database first? Our SQL tricks for cleaner queries let the database do the dedupe and grouping before it ever reaches your JavaScript.
FAQ
Do these one-liners work in the browser?
Yes, in current versions of Chrome, Firefox, Safari and Edge. sleep() with a top-level await needs a module script or an async function.
Which Node version do I need?
Node 22 or newer runs all 20. We tested on Node 24. Object.groupBy() needs 21+, and the new Set methods need 22+.
Is structuredClone slower than JSON.parse(JSON.stringify())?
It depends on the data, and we didn’t benchmark it. Pick it for correctness: it handles dates, maps, sets and circular references, which the JSON trick doesn’t.
Should I still use Lodash?
For new code on modern runtimes, often not. Built-ins now cover grouping, cloning and set operations. Lodash still has handy helpers like debounce that the language doesn’t ship.