DEV Community

Cover image for 25+ Essential JavaScript One-Liners You Need to Know in 2025 πŸš€πŸ”₯
Aniket
Aniket

Posted on

7 3 3 3 3

25+ Essential JavaScript One-Liners You Need to Know in 2025 πŸš€πŸ”₯

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);
Enter fullscreen mode Exit fullscreen mode

Uses the spread operator to pass elements as arguments to Math.max().

2. Remove Duplicates from an Array

[...new Set(array)];
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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)];
Enter fullscreen mode Exit fullscreen mode

Selects a random element from an array.

5. Get the Last Item of an Array

const lastItem = (arr) => arr.at(-1);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Returns true if the object has no properties.

8. Merge Multiple Objects

const mergeObjects = (...objs) => Object.assign({}, ...objs);
Enter fullscreen mode Exit fullscreen mode

Combines multiple objects into one.

9. Deep Clone an Object

const clone = (obj) => structuredClone(obj);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

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()];
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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, '-');
Enter fullscreen mode Exit fullscreen mode

Replaces spaces with hyphens and ensures lowercase formatting.

14. Reverse a String

const reverseString = (str) => [...str].reverse().join('');
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

Performs a case-insensitive substring check.

17. Generate a Random Alphanumeric String

const randomAlphaNum = (length) => [...Array(length)].map(() => (Math.random().toString(36)[2])).join('');
Enter fullscreen mode Exit fullscreen mode

Generates a random alphanumeric string of a given length.


Utility Functions

18. Get the Current Timestamp

Date.now();
Enter fullscreen mode Exit fullscreen mode

Returns the current timestamp in milliseconds.

19. Check if a Variable is an Array

Array.isArray(variable);
Enter fullscreen mode Exit fullscreen mode

Returns true if the variable is an array.

20. Convert Query Parameters to an Object

const parseQuery = (url) => Object.fromEntries(new URL(url).searchParams);
Enter fullscreen mode Exit fullscreen mode

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];
Enter fullscreen mode Exit fullscreen mode

Extracts the date portion from an ISO date string.

22. Shorten an Array by Removing Falsy Values

const cleanArray = (arr) => arr.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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')}`;
Enter fullscreen mode Exit fullscreen mode

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)}`;
Enter fullscreen mode Exit fullscreen mode

Converts RGB values to a HEX color code.

26. Generate a UUID (Version 4)

const uuid = () => crypto.randomUUID();
Enter fullscreen mode Exit fullscreen mode

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);
    });

Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
rjbudzynski profile image
rjbudzynski β€’

Some of these (like 9, 10, 26) are just renaming existing functions.

Collapse
 
ananiket profile image
Aniket β€’ β€’ Edited

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!

Collapse
 
Sloan, the sloth mascot
Comment deleted