20 JavaScript One-Liners That Will Make You Look Like a Pro

Ishan Bagchi - Feb 1 - - Dev Community

JavaScript is full of surprises, and its flexibility allows developers to write some incredibly concise yet powerful one-liners. These snippets can be useful, confusing, or just plain fun! In this blog, we'll explore some crazy JavaScript one-liners and break them down for you.


1. Swap Two Variables Without a Temp Variable

[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

How? This uses array destructuring to swap values without needing a temporary variable.


2. Check If a Number Is Even

const isEven = n => !(n & 1);
Enter fullscreen mode Exit fullscreen mode

How? The bitwise AND (&) checks if the least significant bit is 1 (odd) or 0 (even).


3. Reverse a String

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

How? The spread operator (...) converts the string into an array, which is reversed and joined back into a string.


4. Generate a Random Hex Color

const randomColor = () => `#${Math.floor(Math.random()*0xFFFFFF).toString(16).padStart(6, '0')}`;
Enter fullscreen mode Exit fullscreen mode

How? A random number is generated and converted to a hex string, ensuring it’s always 6 characters long.


5. Get the Last Item of an Array

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

How? .at(-1) gets the last element of an array in a clean and readable way.


6. Flatten a Nested Array

const flatArray = arr => arr.flat(Infinity);
Enter fullscreen mode Exit fullscreen mode

How? .flat(Infinity) recursively flattens an array of any depth.


7. Convert a String to a Number

const toNumber = str => +str;
Enter fullscreen mode Exit fullscreen mode

How? The + operator converts a string to a number in a super concise way.


8. Remove Duplicates from an Array

const uniqueArray = arr => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

How? Set removes duplicates, and the spread operator converts it back to an array.


9. Find the Intersection of Two Arrays

const intersection = (a, b) => a.filter(x => b.includes(x));
Enter fullscreen mode Exit fullscreen mode

How? It filters elements in a that exist in b.


10. Shuffle an Array

const shuffle = arr => arr.sort(() => Math.random() - 0.5);
Enter fullscreen mode Exit fullscreen mode

How? Random sorting creates a simple shuffle (though not the most optimal way).


11. Get the Current Timestamp

const timestamp = () => Date.now();
Enter fullscreen mode Exit fullscreen mode

How? Date.now() returns the number of milliseconds since January 1, 1970.


12. Short-Circuit Default Values

const greet = name => name || 'Guest';
Enter fullscreen mode Exit fullscreen mode

How? If name is falsy (like null or undefined), 'Guest' is used instead.


13. Count Occurrences of an Element in an Array

const countOccurrences = (arr, val) => arr.reduce((a, v) => v === val ? a + 1 : a, 0);
Enter fullscreen mode Exit fullscreen mode

How? reduce iterates and counts occurrences of val.


14. Get a Random Item from an Array

const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];
Enter fullscreen mode Exit fullscreen mode

How? Math.random() picks a random index from the array.


15. 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

How? Bitwise operations and .toString(16) convert RGB values to hex format.


16. Check If a String Is a Palindrome

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

How? The string is reversed and compared to the original.


17. Convert a Boolean to a Number

const boolToNumber = bool => +bool;
Enter fullscreen mode Exit fullscreen mode

How? The + operator converts true to 1 and false to 0.


18. Capitalize the First Letter of a String

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
Enter fullscreen mode Exit fullscreen mode

How? The first character is converted to uppercase and concatenated with the rest of the string.


19. Remove Whitespace from a String

const trimSpaces = str => str.replace(/\s+/g, '');
Enter fullscreen mode Exit fullscreen mode

How? The regex /\s+/g removes all whitespace characters.


20. Generate a Random Boolean

const randomBoolean = () => Math.random() >= 0.5;
Enter fullscreen mode Exit fullscreen mode

How? Math.random() generates a number between 0 and 1, returning true or false based on a threshold.


Conclusion

JavaScript one-liners are a great way to write concise, elegant, and sometimes tricky code. While they can be impressive, always prioritize readability and maintainability in production code. Have a favourite one-liner? Please share it in the comments!

. . . . . . . . .