JavaScript is famous for its flexibility and power, but did you know it can be surprisingly elegant too? One-liners are compact code snippets that can accomplish tasks beautifully, and they’re great for impressing your peers or simplifying your workflow. Here are 25 JavaScript one-liners that will blow your mind.
1. Reverse a String
const reverseString = str => [...str].reverse().join('');
Use Case: Quickly reverse any string, such as reverseString('hello') // 'olleh'
.
Practical Value: Useful in scenarios where reversing text is part of a functionality, such as processing user input or handling strings in algorithms.
2. Check for Palindrome
const isPalindrome = str => str === [...str].reverse().join('');
Use Case: Validate palindromes like isPalindrome('racecar') // true
.
Practical Value: Commonly used in interview problems, text validations, or fun applications like games or word-based puzzles.
3. Flatten an Array
const flatten = arr => arr.flat(Infinity);
Use Case: flatten([1, [2, [3, [4]]]]) // [1, 2, 3, 4]
.
Practical Value: Essential for working with deeply nested datasets, such as JSON responses from APIs.
4. Generate a Random Hex Color
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')}`;
Use Case: Dynamically generate colors for themes or charts: randomHex() // #1a2b3c
.
Practical Value: Perfect for creating unique color palettes in design tools or dynamic visuals in web applications.
5. Get the Maximum Value in an Array
const max = arr => Math.max(...arr);
Use Case: max([10, 20, 30]) // 30
.
Practical Value: Frequently used in statistical analysis or to find extremes in numerical datasets.
6. Count Occurrences in an Array
const countOccurrences = (arr, val) => arr.reduce((a, v) => v === val ? a + 1 : a, 0);
Use Case: countOccurrences([1, 2, 2, 3], 2) // 2
.
Practical Value: Ideal for analytics, such as counting specific user actions or identifying duplicates in datasets.
7. Capitalize the First Letter of a String
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
Use Case: capitalize('hello') // 'Hello'
.
Practical Value: Useful for formatting user input or displaying properly formatted text in UI elements.
8. Remove Duplicates from an Array
const unique = arr => [...new Set(arr)];
Use Case: unique([1, 2, 2, 3]) // [1, 2, 3]
.
Practical Value: Simplifies handling unique values in large datasets, commonly seen in search or recommendation systems.
9. Get Query Parameters from a URL
const getParams = url => Object.fromEntries(new URL(url).searchParams);
Use Case: getParams('https://example.com?name=John&age=30') // { name: 'John', age: '30' }
.
Practical Value: A lifesaver when working with APIs or building tools that need to parse URLs for dynamic content.
10. Check if a Year is a Leap Year
const isLeapYear = year => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
Use Case: isLeapYear(2024) // true
.
Practical Value: Commonly applied in calendar-based systems, scheduling algorithms, or date validation tools.
11. Sort an Array of Numbers
const sortNumbers = arr => [...arr].sort((a, b) => a - b);
Use Case: Sort numerical data: sortNumbers([3, 1, 4, 2]) // [1, 2, 3, 4]
.
Practical Value: Simplifies sorting operations in projects involving statistics or rankings.
12. Check if an Array is Empty
const isEmpty = arr => arr.length === 0;
Use Case: isEmpty([]) // true
.
Practical Value: Useful for validating input or initializing data checks in functions.
13. Convert Fahrenheit to Celsius
const toCelsius = f => (f - 32) * 5 / 9;
Use Case: toCelsius(98.6) // 37
.
Practical Value: Handy for weather apps or any project involving temperature conversion.
14. Filter Falsy Values
const filterFalsy = arr => arr.filter(Boolean);
Use Case: filterFalsy([0, "", null, 42]) // [42]
.
Practical Value: Cleans up datasets by removing invalid or unnecessary values.
15. Calculate Factorial
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
Use Case: factorial(5) // 120
.
Practical Value: Commonly used in algorithms, math-based programs, or educational projects.
16. Merge Objects
const merge = (obj1, obj2) => ({ ...obj1, ...obj2 });
Use Case: merge({ a: 1 }, { b: 2 }) // { a: 1, b: 2 }
.
Practical Value: Simplifies combining configurations or dynamic data structures.
17. Check for Prime Number
const isPrime = num => num > 1 && ![...Array(num).keys()].slice(2).some(i => num % i === 0);
Use Case: isPrime(7) // true
.
Practical Value: Great for teaching programming logic or creating number-based challenges.
18. Generate a Range of Numbers
const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => start + i);
Use Case: range(1, 5) // [1, 2, 3, 4, 5]
.
Practical Value: Great for creating test data or iterating through numeric ranges.
19. Convert a Number to Binary
const toBinary = num => num.toString(2);
Use Case: toBinary(10) // "1010"
.
Practical Value: Useful in low-level programming or when optimizing performance.
20. Get Random Element from Array
const randomElement = arr => arr[Math.floor(Math.random() * arr.length)];
Use Case: randomElement(["apple", "banana", "cherry"]) // "banana"
.
Practical Value: Adds randomness in applications like games or quizzes.
21. Repeat a String
const repeatString = (str, times) => str.repeat(times);
Use Case: repeatString("ha", 3) // "hahaha"
.
Practical Value: Simplifies creating patterns or repetitive data.
22. Sum of Array Elements
const sumArray = arr => arr.reduce((sum, num) => sum + num, 0);
Use Case: sumArray([1, 2, 3]) // 6
.
Practical Value: Frequently used in statistics or to calculate totals.
23. Trim Whitespace from a String
const trimWhitespace = str => str.trim();
Use Case: trimWhitespace(" hello ") // "hello"
.
Practical Value: Helpful for cleaning user input or formatting text.
24. Get Unique Values from Multiple Arrays
const uniqueFromArrays = (...arrays) => [...new Set(arrays.flat())];
Use Case: uniqueFromArrays([1, 2], [2, 3]) // [1, 2, 3]
.
Practical Value: Combines and deduplicates multiple datasets efficiently.
25. Get Day Name from Date
const getDayName = date => new Date(date).toLocaleDateString('en-US', { weekday: 'long' });
Use Case: getDayName("2025-01-05") // "Sunday"
.
Practical Value: Useful in scheduling apps or calendars.
Why These One-Liners Matter
JavaScript one-liners like these are not just about being clever. They simplify code, make your solutions more elegant, and often run more efficiently. Plus, they’re a great way to learn advanced features like destructuring, ES6 methods, and functional programming.
In real-world applications, these one-liners can make your codebase more readable and concise. They save time during development, reduce the chance of errors, and ensure maintainability, especially in collaborative projects.
You Might Also Like
- Node.js Design Patterns and Best Practices for Scalable Apps
- Advanced Jest Techniques: Mocks, Spies, and Stubs
- Common Mistakes When Using Redux and How to Avoid Them
- Building a PWA with JavaScript: A Developer’s Guide
- Sharding in MongoDB: How It Works and Why It Matters
Wrap-Up
Mastering these JavaScript one-liners can help you write cleaner, smarter, and faster code. From practical utilities like removing duplicates to fun tricks like generating random colors, there’s something for every developer. Start incorporating them into your projects today, and don’t forget to share your favorite one-liners in the comments below!