JavaScript is a versatile and expressive language, and it's often said that you can do a lot with just a single line of code. In this article, we'll explore 10 JavaScript one-liners that are not only concise but also incredibly useful. These one-liners can simplify your code and make it more elegant. Let's dive in!
1. Random Color Generator
Need a random color for styling elements? This one-liner generates a random hex color code:
const randomColor = () => `#${Math.random().toString(16).slice(2, 8)}`;2. Shuffle an Array
Shuffling an array is a common task, especially for randomizing elements. Here's a one-liner to shuffle an array in place:
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);3. Get Unique Values from an Array
Removing duplicate values from an array is straightforward with this one-liner:
const uniqueValues = arr => [...new Set(arr)];4. Check for Palindromes
Determine if a string is a palindrome (reads the same backward as forward) with this concise one-liner:
const isPalindrome = str => str === str.split('').reverse().join('');5. Find Maximum Value in an Array
Find the maximum value in an array with ease using the spread operator:
const maxInArray = arr => Math.max(...arr);6. Flatten an Array
If you have a nested array and want to make it flat, this one-liner does the trick:
const flattenArray = arr => arr.flat(Infinity);7. Calculate Factorials
Compute factorials in a compact manner with this recursive one-liner:
const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);8. Count Occurrences in an Array
Count the occurrences of a specific element in an array with this elegant one-liner:
const countOccurrences = (arr, elem) => arr.reduce((count, e) => e === elem ? count + 1 : count, 0);9. Convert String to Title Case
Transforming a string into title case is a breeze with regular expressions:
const toTitleCase = str => str.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());10. Get Current Date in a Specific Format
Retrieve the current date in a locale-specific format with this one-liner:
const currentDate = () => new Date().toLocaleDateString('en-US');These JavaScript one-liners are not only efficient but also serve as powerful tools in your coding arsenal. They demonstrate the beauty of concise code that achieves complex tasks. Incorporating them into your projects can lead to cleaner, more readable code and enhance your development experience. Happy coding!
