13 Remarkable JavaScript One-Liners That Will Show Your Mastery

In programming, there are usually multiple ways to solve the same problem. These solutions can vary in different areas, such as the length, performance, algorithm used, readability, and so on.
In this article, we'll be looking at several quick and concise one-liner solutions to various problems that frequently arise in JavaScript.
Every Crazy Thing JavaScript Does

What is a One-Liner?
Before we begin, let's make sure we understand what makes a piece of code a one-liner.
A one-liner is code solution to a problem, implemented with a single statement in a particular programming language, without any third-party utilities.
This definition contains important differentiating features you don't find in a lot of others:
1. "...single statement..."
Not every piece of code that takes up only one line is a one-liner. For example, look at this method that adds the sum of two squares and returns the result.
const sum = (a, b) => { const s1 = a * a; const s2 = b * b; return s1 + s2; }
Would you call this a one-liner? In most cases, this would just pass as badly formatted code. Tools like Prettier will easily automatically split up the three statements into multiple lines.

A true one-liner way to get the sum of two squares would be something like this:
const sum = (a, b) => a * a + b * b;
One short, succinct statement does the same job with equal clarity.
On the other hand, this method spans multiple lines of code for greater readability, but it can still pass as a one-liner:
const capitalizeWithoutSpaces = (str) =>
str
.split('')
.filter((char) => char.trim())
.map((char) => char.toUpperCase())
.join('');
So despite the name, "one-liner" does not necessarily mean one line of code.
2. "...particular programming language..."
This has to do with the fact that every high-level language program has to be translated to lower-level languages before execution. One very simple program could end up taking dozens or hundreds of lines in assembly and machine code.
For example, here is another one-liner that also adds the sum of two squares, this time in C++:
int sum(int a, int b) {
return a * a + b * b;
}
Let's see what it looks like, after compilation to assembly language:
sum(int, int):
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
mov eax, DWORD PTR [rbp-4]
imul eax, eax
mov edx, eax
mov eax, DWORD PTR [rbp-8]
imul eax, eax
add eax, edx
pop rbp
ret
This assembly program obviously has more than one line or statement of code. Imagine how much more an equivalent machine language program will have. So the function can be said to be a one-liner only within the context of C++.
3. "...without any third-party utilities"
For a piece of code to be a one-liner, it should not reference any methods or functions that are not natively available in the programming language. Remember the one-liner we looked at earlier:
const capitalizeWithoutSpaces = (str) =>
str
.split('')
.filter((char) => char.trim())
.map((char) => char.toUpperCase())
.join('');
All the methods used here are built-in JavaScript methods. It doesn't include third-party code from NPM or elsewhere.
If, however, we decide to implement our own filter()
method to replace Array
filter()
, the method would no longer qualify as a one-liner.
// Not a one-liner
const capitalizeWithoutSpaces = (str) =>
filter(str.split(''), (char) => char.trim())
.map((char) => char.toUpperCase())
.join('');
function filter(arr, callback) {
// Look at all these lines
const result = [];
for (const item of arr) {
if (callback(item)) {
result.push(item);
}
}
return result;
}
With the definition out of the way, let's now look at a number of intelligent JavaScript one-liners and the problems they solve.
1. Get the Smallest Element of an Array
To get the smallest item in an array, we could take this imperative approach that uses a for
loop and an if
statement.
const getSmallest = (arr) => {
let smallest = Number.POSITIVE_INFINITY;
for (const num of arr) {
if (num < smallest) {
smallest = num;
}
}
return smallest;
};
const arr = [13, 7, 11, 3, 9, 15, 17];
console.log(getSmallest(arr)); // 3
This is alright, but there is a concise and declarative one-liner alternative that works just as well:
const getSmallest = (arr) =>
arr.reduce((smallest, num) => Math.min(smallest, num));
const arr = [13, 7, 11, 3, 9, 15, 17];
console.log(getSmallest(arr)); // 3
2. Get the Largest Element of an Array
This is an acceptable way of getting the largest element in an array.
const getLargest = (arr) => {
let largest = Number.NEGATIVE_INFINITY;
for (const num of arr) {
if (num > largest) {
largest = num;
}
}
return largest;
};
const arr = [13, 7, 11, 3, 9, 15, 17];
console.log(getLargest(arr)); // 17
But just like we saw for getting the smallest array element, there is a much shorter and concise approach.
const getLargest = (arr) =>
arr.reduce((largest, num) => Math.max(largest, num));
const arr = [13, 7, 11, 3, 9, 15, 17];
console.log(getLargest(arr)); // 17
You can see that the only difference between this and the one-liner getSmallest()
function is that Math.min()
has been replaced with Math.max()
.
3. Shuffle an Array
A common use of array/list shuffling is in a card game, where the cards in the deck have to be randomly ordered.
The Fisher-Yates shuffle is a well-known shuffling algorithm. Look at a possible implementation of it in JavaScript:
const shuffleArray = (arr) => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
};
const arr = [1, 2, 3, 4, 5];
shuffleArray(arr);
// [ 2, 3, 5, 1, 4 ] (varies)
console.log(arr);
Refactor this with some functional programming magic and we have:
const shuffleArray = (arr) =>
[...Array(arr.length)]
.map((_, i) => Math.floor(Math.random() * (i + 1)))
.reduce(
(shuffled, r, i) =>
shuffled.map((num, j) =>
j === i ? shuffled[r] : j === r ? shuffled[i] : num
),
arr
);
// [ 2, 4, 1, 3, 5 ] (varies)
console.log(shuffleArray([1, 2, 3, 4, 5]));
This runs with O(n2)
time complexity (quadratic), and could cause performance problems for large arrays, but it is an elegant solution that works. Also, unlike the first method, it doesn't mutate the original array.
An alternative functional approach takes advantage of how the Array
sort()
method is implemented to shuffle an array.
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
const arr = [1, 2, 3, 4, 5];
// [ 5, 2, 4, 1, 3 ] (varies)
console.log(shuffleArray(arr));
As it uses sort()
, it runs with a time complexity of O(n log n)
and has a better performance than the preceding method.
4. Group an Array By an Object Property
Sometimes we need to group an array of objects using a specific property they all have, e.g., grouping users by country, grouping books by year published, grouping cars by color, etc.
In the following example, we group person objects in an array according to the length of their names.
const groupBy = (arr, groupFn) => {
const grouped = {};
for (const obj of arr) {
const groupName = groupFn(obj);
if (!grouped[groupName]) {
grouped[groupName] = [];
}
grouped[groupName].push(obj);
}
return grouped;
};
const people = [
{ name: 'Matt' },
{ name: 'Sam' },
{ name: 'John' },
{ name: 'Mac' },
];
const groupedByNameLength = groupBy(people, (person) => person.name.length);
/**
{
'3': [ { name: 'Sam' }, { name: 'Mac' } ],
'4': [ { name: 'Matt' }, { name: 'John' } ]
}
*/
console.log(groupedByNameLength);
And here is the one-liner:
const groupBy = (arr, groupFn) =>
arr.reduce(
(grouped, obj) => ({
...grouped,
[groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj],
}),
{}
);
const people = [
{ name: 'Matt' },
{ name: 'Sam' },
{ name: 'John' },
{ name: 'Mac' },
];
const groupedByNameLength = groupBy(people, (person) => person.name.length);
/**
{
'3': [ { name: 'Sam' }, { name: 'Mac' } ],
'4': [ { name: 'Matt' }, { name: 'John' } ]
}
*/
console.log(groupedByNameLength);
5. Reverse a String
We could reverse a string in JavaScript using a reverse for
loop like this:
const reverseString = (str) => {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
const ch = str[i];
reversed += ch;
}
return reversed;
};
const reverse = reverseString('javascript');
console.log(reverse); // tpircsavaj
But once again, we can take utilize the powerful built-in Array
methods like reverse()
and join()
to create a one-liner that does the same thing.
const reverseString = (str) => str.split('').reverse().join('');
const reverse = reverseString('javascript');
console.log(reverse); // tpircsavaj
6. Generate a Random Hex Color
Hex color codes are a way of specifying RGB colors. They have a #RRGGBB
format, where RR
represents red, GG
represents green, and BB represents blue
. The values of each color range from 0
to 255
, and are represented in hexadecimal format - 0
to FF
.
This one-liner generates a random hex color and returns the result.
const randomHexColor = () =>
`#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
console.log(randomHexColor()); // #7a10ba (varies)
console.log(randomHexColor()); // #65abdc (varies)
7. Check if Two Arrays Contain the Same Values
This is a problem of ensuring that two arrays contain the same elements (in any order) and that these elements occur the same number of times in both arrays.
Using a for
loop, we can implement the following solution:
const areEqual = (arr1, arr2) => {
if (arr1.length === arr2.length) {
for (const num of arr1) {
if (!arr2.includes(num)) {
return false;
}
}
return true;
}
return false;
};
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 1, 2];
const arr3 = [1, 2, 3];
console.log(areEqual(arr1, arr2)); // true
console.log(areEqual(arr1, arr3)); // false
Using the Array
sort()
and join()
methods, we can create a one-liner alternative:
const areEqual = (arr1, arr2) =>
arr1.sort().join(',') === arr2.sort().join(',');
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 1, 2];
const arr3 = [1, 2, 3];
console.log(areEqual(arr1, arr2)); // true
console.log(areEqual(arr1, arr3)); // false
8. Remove Duplicates from an Array
We could remove duplicates from an array like this:
const removeDuplicates = (arr) => {
const result = [];
for (const num of arr) {
if (!result.includes(num)) {
result.push(num);
}
}
return result;
};
const arr = [1, 2, 3, 4, 5, 3, 1, 2, 5];
const distinct = removeDuplicates(arr);
console.log(distinct); // [1, 2, 3, 4, 5]
But we can make use of the Set()
constructor to remove the duplicates in one short line:
const removeDuplicates = (arr) => [...new Set(arr)];
const arr = [1, 2, 3, 4, 5, 3, 1, 2, 5];
const distinct = removeDuplicates(arr);
console.log(distinct); // [1, 2, 3, 4, 5]
9. Convert a Map to JSON
This short function lets us quickly convert a Map object to a JSON string without losing any information:
const mapToJson = (map) => JSON.stringify(Object.fromEntries(map));
const map = new Map([
['user1', 'John'],
['user2', 'Kate'],
['user3', 'Peter'],
]);
const json = mapToJson(map);
// {"user1":"John","user2":"Kate","user3":"Peter"}
console.log(json);
10. Convert JSON to a Map
Another one-liner can reverse the conversion above. The following function will convert a JSON string to a Map object.
const jsonToMap = (json) => new Map(Object.entries(JSON.parse(json)));
const json = '{"user1":"John","user2":"Kate","user3":"Peter"}';
const map = jsonToMap(json);
// Kate
console.log(map.get('user2'));
// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);
11. Convert a String in Snake Case to Camel Case
In a string in snake case, each word is separated by an underscore (_
) and begins with a lowercase letter, for example: variable_name
, bread_and_eggs
, etc.
For a string in camel case though, the first word begins with a lowercase letter, and the following words each start with an uppercase letter. There are no spaces or punctuation separating the words. Examples of camel case strings are: variableName
, breadAndEggs
, etc.
Using this concise function, we can convert any string in snake case to camel case.
const snakeToCamelCase = (s) =>
s.toLowerCase().replace(/(_\w)/g, (w) => w.toUpperCase().substr(1));
const str1 = 'learn_javascript';
const str2 = 'coding_beauty';
console.log(snakeToCamelCase(str1)); // learnJavaScript
console.log(snakeToCamelCase(str2)); // codingBeauty
12. Generate a Random UUID
"UUID" is an acronym for University Unique Identifier. A UUID is a 128-bit value that unique identifies an object or entity on the internet.
This one-liner generates a random UUID:
const generateRandomUUID = (a) =>
a
? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
: ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(
/[018]/g,
generateRandomUUID
);
console.log(generateRandomUUID()); // f138f635-acbd-4f78-9be5-ca3198c4cf34
console.log(generateRandomUUID()); // 8935bb0d-6503-441f-bb25-7bc685b5b5bc
13. Conditional Flow Control using Nested Ternary Operators
We can use nested ternary operators to transform an if...else
or switch
statement into a one-liner. Consider a function that returns the English word form of a number within a certain range.
Using an if...else
statement, such a function can be implemented like this:
const getNumWord = (num) => {
if (num === 1) {
return 'one';
} else if (num === 2) {
return 'two';
} else if (num === 3) {
return 'three';
} else if (num === 4) {
return 'four';
} else return 'unknown';
};
console.log(getNumWord(1)); // one
console.log(getNumWord(3)); // three
console.log(getNumWord(7)); // unknown
Using a switch...case
statement:
const getNumWord = (num) => {
switch (num) {
case 1:
return 'one';
case 2:
return 'two';
case 3:
return 'three';
case 4:
return 'four';
default:
return 'unknown';
}
};
console.log(getNumWord(1)); // one
console.log(getNumWord(3)); // three
console.log(getNumWord(7)); // unknown
And now using nested ternaries to create the one-liner:
const getNumWord = (num) =>
num === 1
? 'one'
: num === 2
? 'two'
: num === 3
? 'three'
: num === 4
? 'four'
: 'unkwown';
console.log(getNumWord(1)); // one
console.log(getNumWord(3)); // three
console.log(getNumWord(7)); // unknown
Conclusion
We've looked at concise JavaScript solutions to common programming problems. We saw many instances where the imperative solution consisting of multiple statements was transformed into a declarative one-liner using various built-in methods and language constructs. These compact solutions sometimes have lower performance and readability, but using them can demonstrate your programming ability and mastery of the language.
11 Amazing New Features in ES13

See also
- This is how functional try-catch transforms your JavaScript code
- Your 10 Best JavaScript Books for Complete Mastery in 2023
- This if statement alternative only works in JavaScript
- 7 amazing new JavaScript features in ES14 (ES2023)
- 7 little-known but powerful array methods in JavaScript
- Unleashing the power of JavaScript generators: from basics to real-world applications (complete guide)