You’ve probably heard the phrase: “Write less, do more.”
But what if I told you JavaScript can literally do magic in one line?
Let’s dive into 10 game-changing JavaScript one-liners that can make your code cleaner, smarter, and crazy efficient.
If you’re a dev who loves shortcuts that don’t compromise on clarity—you’re going to LOVE this.
1. 📅 Get Today’s Date in YYYY-MM-DD Format
const today = new Date().toISOString().split('T')[0];
✅ Perfect for logging, timestamps, or form defaults.
2. 🔁 Swap Two Variables Without a Temp
[a, b] = [b, a];
💡 Cleaner than the classic temp-variable trick!
3. Generate Random Number Between Min & Max
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
✨ Example: random(1, 100) gives you a number from 1 to 100.
4. 📏 Check If a Number Is Even
const isEven = num => num % 2 === 0;
So simple, yet used everywhere in loops, validations, and conditions.
5. 🧼 Remove Duplicates from an Array
const unique = arr => [...new Set(arr)];
If you're working with large datasets or filtering user input, this is gold.
Want to go deeper on Set in JavaScript?
6. 📦 Flatten a Nested Array
const flatten = arr => arr.flat(Infinity);
Boom. One line. Any level of depth.
7. 📚 Count Occurrences of Items in an Array
const count = arr => arr.reduce((a,v) => (a[v] = (a[v] || 0) + 1, a), {});
🔥 Perfect for analytics, reports, or UI stats.
Example:
count(['apple', 'banana', 'apple', 'orange']);
// Output: { apple: 2, banana: 1, orange: 1 }
8. 🔤 Capitalize the First Letter of Every Word
const capitalizeWords = str => str.replace(/\b\w/g, c => c.toUpperCase());
A lifesaver when formatting names, titles, or labels.
9. 🌐 Copy Text to Clipboard
navigator.clipboard.writeText("Hello, World!");
Use this in custom copy-to-clipboard buttons. Try it in your interactive projects.
10. 🔍 Check if an Object is Empty
const isEmpty = obj => Object.keys(obj).length === 0;
✅ Useful in form validations, conditionals, or API responses.
Want to Practice These?
Check out this 🔗 JavaScript One-Liners Playground (JSFiddle) to try them out live and see the magic.
💬 Which one blew your mind the most?
👇 Drop your favorite one-liner in the comments or share your own secret trick!
👉 Follow DCT Technology for more mind-blowing JavaScript gems, dev tips, and tools that help you code smarter.