Hello Devs! Welcome back to another article.
JavaScript continues to evolve, providing developers with more concise and efficient ways to write code. Whether you're an experienced programmer or just starting your journey, mastering these modern one-liners can significantly enhance your productivity.
These modern JavaScript one-liners will streamline your development workflow in 2025, helping you write cleaner, faster, and more efficient code.
Array Manipulations
1. Find the Maximum Value in an Array
Math.max(...array);
Uses the spread operator to pass elements as arguments to Math.max().
2. Remove Duplicates from an Array
[...new Set(array)];
Converts the array to a Set (which removes duplicates) and back to an array.
3. Flatten a Nested Array
const flatten = (arr) => arr.flat(Infinity);
Flattens an array to any depth using flat(Infinity).
4. Get a Random Element from an Array
const randomElement = (arr) => arr[Math.floor(Math.random() * arr.length)];
Selects a random element from an array.
5. Get the Last Item of an Array
const lastItem = (arr) => arr.at(-1);
Uses .at(-1) for cleaner syntax to get the last element.
6. Get the First N Elements of an Array
const firstN = (arr, n) => arr.slice(0, n);
Extracts the first n elements from an array.
Object Utilities
7. Check if an Object is Empty
const isEmptyObject = (obj) => Object.keys(obj).length === 0;
Returns true if the object has no properties.
8. Merge Multiple Objects
const mergeObjects = (...objs) => Object.assign({}, ...objs);
Combines multiple objects into one.
9. Deep Clone an Object
const clone = (obj) => structuredClone(obj);
Uses the built-in structuredClone() method for deep cloning.
(Enhanced for Compatibility π)
Instead of just structuredClone(obj), provide a fallback for older browsers:
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
Why? structuredClone(obj) is modern but not supported in all environments. This alternative works in most cases, except when cloning functions or undefined values.
10. Convert an Object to an Array
const objToArray = (obj) => Object.entries(obj);
Turns an object into an array of key-value pairs.
(With Sorting Option π)
Instead of just Object.entries(obj), allow sorting:
const objToArray = (obj, sort = false) => {
const entries = Object.entries(obj);
return sort ? entries.sort(([keyA], [keyB]) => keyA.localeCompare(keyB)) : entries;
};
Why? Adds a sorting option, making the function more flexible for use cases where ordered key-value pairs are needed.
11. Get Unique Elements from an Array of Objects (by Property)
const uniqueBy = (arr, key) => [...new Map(arr.map(item => [item[key], item])).values()];
Filters unique objects based on a specific property.
String Operations
12. Capitalize the First Letter of a String
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
Capitalizes only the first letter while keeping the rest unchanged.
13. Convert a String to a Slug
const slugify = (str) => str.toLowerCase().trim().replace(/\s+/g, '-');
Replaces spaces with hyphens and ensures lowercase formatting.
14. Reverse a String
const reverseString = (str) => [...str].reverse().join('');
Splits the string into an array, reverses it, and joins it back.
15. Count Occurrences of a Character in a String
const countChar = (str, char) => str.split(char).length - 1;
Counts how many times a specific character appears in a string.
16. Check if a String Contains a Substring (Case Insensitive)
const containsIgnoreCase = (str, substr) => str.toLowerCase().includes(substr.toLowerCase());
Performs a case-insensitive substring check.
17. Generate a Random Alphanumeric String
const randomAlphaNum = (length) => [...Array(length)].map(() => (Math.random().toString(36)[2])).join('');
Generates a random alphanumeric string of a given length.
Utility Functions
18. Get the Current Timestamp
Date.now();
Returns the current timestamp in milliseconds.
19. Check if a Variable is an Array
Array.isArray(variable);
Returns true if the variable is an array.
20. Convert Query Parameters to an Object
const parseQuery = (url) => Object.fromEntries(new URL(url).searchParams);
Parses query parameters from a URL into an object.
21. Format a Date in YYYY-MM-DD Format
const formatDate = (date) => date.toISOString().split('T')[0];
Extracts the date portion from an ISO date string.
22. Shorten an Array by Removing Falsy Values
const cleanArray = (arr) => arr.filter(Boolean);
Removes false, 0, null, undefined, NaN, and "" from an array.
Randomization & Color Utilities
23. Generate a Random Integer Between Two Values (Inclusive)
const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
Efficiently generates a random number within the specified range.
24. Generate a Random HEX Color
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
Generates a random hexadecimal color code.
25. Convert RGB to HEX
const rgbToHex = (r, g, b) => `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1)}`;
Converts RGB values to a HEX color code.
26. Generate a UUID (Version 4)
const uuid = () => crypto.randomUUID();
Uses the built-in crypto module to generate a unique identifier.
(Alternative for Older Browsers) π
Instead of just crypto.randomUUID(), create a UUID manually:
const uuid = () =>
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
const rand = (Math.random() * 16) | 0;
return (char === 'x' ? rand : (rand & 0x3) | 0x8).toString(16);
});
Why? crypto.randomUUID() is modern but not available in all browsers. This method provides a reliable fallback.
Update: Based on feedback, weβve improved some one-liners (9, 10, 26) to add more functionality beyond built-in methods.
Final Thoughts
Mastering these JavaScript one-liners will make your code cleaner, more efficient, and easier to maintain. Whether you're optimizing performance or improving readability, these techniques will save you time and effort in 2025.
Do you have a favorite one-liner thatβs not on this list? Share it in the comments below! π
Top comments (3)
Some of these (like 9, 10, 26) are just renaming existing functions.
Thanks for the feedback! You're right that some of these (like 9, 10, 26) are built-in functions wrapped in a more accessible way. The goal of this article was to highlight useful one-liners that developers can quickly reference, even if some are direct mappings to existing methods. That said, I appreciate the insight, and I might update the article to clarify which ones are purely built-in vs. more complex utilities. Let me know if you have any suggestions!