🧠 Introduction
As developers, we’re constantly looking for ways to write cleaner, shorter, and more efficient code. Over time, I’ve picked up some powerful JavaScript one-liners that help me speed up development, simplify logic, and even impress teammates during code reviews.
In this post, I’ll share my 10 favorite JavaScript one-liners I use regularly — with real examples and tips for when to use them.
🔟 1. Remove Duplicates from an Array
const unique = [...new Set([1, 2, 2, 3, 4, 4])];
// [1, 2, 3, 4]
✅ Great for cleaning up data or ensuring unique values in a form or filter.
9️⃣ 2. Swap Two Variables
[a, b] = [b, a];
✅ Simple and clean — no temp variable needed.
8️⃣ 3. Short-Circuit Default Values
const name = user.name || "Guest";
✅ A quick fallback if a value is undefined or falsy.
7️⃣ 4. Check if a Number is Even
const isEven = num => num % 2 === 0;
✅ Works great inside conditionals, filters, or validators.
6️⃣ 5. Flatten an Array
const flat = arr.flat(Infinity);
✅ Removes all levels of nesting in one go.
5️⃣ 6. Generate a Random Hex Color
const color = '#' + Math.floor(Math.random()*16777215).toString(16);
✅ Perfect for random themes, gradients, or creative UIs.
4️⃣ 7. Count Occurrences in an Array
const count = arr.reduce((a, v) => (a[v] = (a[v] || 0) + 1, a), {});
✅ Handy for analytics, tagging systems, or filtering results.
3️⃣ 8. Get the Last Item of an Array
const last = arr.at(-1);
✅ Cleaner than arr[arr.length - 1]
.
2️⃣ 9. Capitalize the First Letter
const cap = str => str.charAt(0).toUpperCase() + str.slice(1);
✅ Great for formatting names, titles, or headings.
1️⃣ 10. Delay with Promises
const wait = ms => new Promise(res => setTimeout(res, ms));
✅ Useful for delays in async flows, animations, or retries.
📌 Final Thoughts
These one-liners aren’t just clever tricks — they’re practical tools I use in real projects.
By mastering these patterns, you’ll not only write less code, but also improve your ability to think functionally and write expressively in JavaScript.
🚀 Try using 2–3 of these in your next project and feel the difference!
💬 Got your own favorite one-liner? Drop it in the comments and let’s build the ultimate list!
🔁 Save this post for future quick wins in your daily coding!
Top comments (0)