DEV Community

Ishan Bagchi for Byte-Sized News

Posted on • Originally published at Medium

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

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!

Top comments (8)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

The random colour one-liner is not quite right - it will never return pure white.

Collapse
 
ishanbagchi profile image
Ishan Bagchi

You're absolutely right! The original one-liner has a tiny flaw: it multiplies by 0xFFFFFF (16777215), which means the maximum value it can generate is0xFFFFFE (16777214) after flooring. This means pure white (#FFFFFF, or 16777215) is never included. To fix this, we can multiply by 0x1000000 (16777216) instead, ensuring the full range of colors, including pure white, is covered. Here's the corrected version:

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

Thanks for catching that! 😊

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Maybe don't use AI to reply 😉

Collapse
 
framemuse profile image
Valery Zinchenko

Why 0x1000000 if you used 1 << 24 before? Inconsistency!

Collapse
 
ayesha_malik_e82fcf402a94 profile image
Ayesha Malik

Great list of JavaScript one-liners! 🔥 These shortcuts make coding more efficient and readable. If you're into lightweight apps, check out Spotify Mod APK, which optimizes performance while unlocking premium features

Collapse
 
morewings profile image
Dima Vyshniakov

Great advices. Except #20, who needs random Boolean values? There are only two of them.

Collapse
 
ishanbagchi profile image
Ishan Bagchi

Random boolean generation can be useful in simulations, testing, or random decision-making algorithms. :-)

Collapse
 
morewings profile image
Dima Vyshniakov

I doubt that this fancy stuff is popular in the front end. Except tests, but with them my point is still valid. Just write true and false cases.