JavaScript continues to evolve, and mastering concise, powerful code patterns can significantly boost your productivity. Here are 10 one-liners that every developer should know in 2024.
1. Shuffle an Array
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
Perfect for randomizing quiz questions or playlist orders!
2. Remove Duplicates from Array
const unique = arr => [...new Set(arr)];
The Set object stores unique values, making deduplication effortless.
3. Check if Array is Empty
const isEmpty = arr => Array.isArray(arr) && arr.length === 0;
Type-safe check that handles edge cases gracefully.
4. Get Random Element from Array
const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];
Great for random quotes, tips, or selecting winners!
5. Capitalize First Letter
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
Essential for formatting user names and titles.
6. Check if Object is Empty
const isEmptyObj = obj => Object.keys(obj).length === 0;
Useful for form validation and API response handling.
7. Deep Clone an Object
const deepClone = obj => JSON.parse(JSON.stringify(obj));
Quick way to create independent copies (note: doesn't handle functions).
8. Generate Random Hex Color
const randomColor = () => `#${Math.floor(Math.random()*16777215).toString(16).padStart(6, '0')}`;
Perfect for dynamic theming and data visualization!
9. Get Current Timestamp
const timestamp = () => Math.floor(Date.now() / 1000);
Unix timestamp in seconds - ideal for APIs and logging.
10. Flatten Nested Array
const flatten = arr => arr.flat(Infinity);
Handles any depth of nesting automatically.
Want More?
If you found these helpful, I've compiled 50+ more JavaScript tips, complete tutorials, and in-depth guides on my blog:
MBloging - JavaScript Tutorials
I cover everything from:
๐ฅ React.js & Next.js deep dives
๐จ CSS tricks and modern layouts
๐ ๏ธ TypeScript best practices
๐ฑ Responsive web development
๐ก Algorithm challenges explained
Let's Connect!
Which one-liner was your favorite? Do you have any JavaScript shortcuts you'd like to share?
Drop a comment below!
Follow me for more web development content, and check out MBloging for comprehensive tutorials and courses!
Top comments (4)
Clean and practical list
Especially liked flat(Infinity) and the hex color generatorโsimple but actually useful. Also checked out mbloging.com, solid resource for JS and frontend content. Keep it up
Appreciate it! Thanks for checking it out ๐
These are great for quick wins and readability. I especially like how beginner-friendly the examples are without feeling trivial. One-liners like this are perfect for learning patterns before diving deeper
Thanks! Glad you found it useful