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];
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);
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('');
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')}`;
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);
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);
How? .flat(Infinity)
recursively flattens an array of any depth.
7. Convert a String to a Number
const toNumber = str => +str;
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)];
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));
How? It filters elements in a
that exist in b
.
10. Shuffle an Array
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
How? Random sorting creates a simple shuffle (though not the most optimal way).
11. Get the Current Timestamp
const timestamp = () => Date.now();
How? Date.now()
returns the number of milliseconds since January 1, 1970.
12. Short-Circuit Default Values
const greet = name => name || 'Guest';
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);
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)];
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)}`;
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('');
How? The string is reversed and compared to the original.
17. Convert a Boolean to a Number
const boolToNumber = bool => +bool;
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);
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, '');
How? The regex /\s+/g
removes all whitespace characters.
20. Generate a Random Boolean
const randomBoolean = () => Math.random() >= 0.5;
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 (7)
The random colour one-liner is not quite right - it will never return pure white.
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 by0x1000000
(16777216) instead, ensuring the full range of colors, including pure white, is covered. Here's the corrected version:Thanks for catching that! 😊
Maybe don't use AI to reply 😉
Why
0x1000000
if you used1 << 24
before? Inconsistency!Great advices. Except #20, who needs random Boolean values? There are only two of them.
Random boolean generation can be useful in simulations, testing, or random decision-making algorithms. :-)
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
andfalse
cases.Some comments may only be visible to logged-in visitors. Sign in to view all comments.