JavaScript is a powerful language. Most of times we are writing long and complex code to get things done. But we have to keep in mind that In fact, we can achieve a lot with just one line of JS code! 🚀
In this article, we will explore 10 mind-blowing JavaScript one-liners that will save our time and make coding fun. Let’s dive in without wasting any time!
Table of Contents
1. Reverse a String Instantly
Want to reverse a string in JavaScript? You don’t need loops. Just use one simple line like below:
const reverseString = str => str.split('').reverse().join('');
console.log(reverseString("JavaScript")); // tpircSavaJ

This code breaks the string into an array, reverses it, and joins it back. It’s a quick way to reverse any string!
2. Check if a Number is Even or Odd
Instead of using an if-else
statement, use this simple one-liner:
const isEven = num => num % 2 === 0;
console.log(isEven(10)); // true

3. Shuffle an Array (Fisher-Yates Algorithm)
Want to randomly shuffle an array? Here is an smart way to do it using one line:
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
console.log(shuffleArray([1, 2, 3, 4, 5]));

This randomizes the order of elements in an array, useful for games, quizzes, and more!
4. Remove Duplicates from an Array
Instead of using loops, use the Set
object and make your code one liner. Amazing right?
const uniqueArray = arr => [...new Set(arr)];
console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]

The Set
object automatically removes duplicates, making this the easiest way to get unique values.
5. Find the Maximum Number in an Array
Forget the for
loop—use Math.max
and spread operator:
const maxNumber = arr => Math.max(...arr);
console.log(maxNumber([10, 20, 5, 8])); // 20

This quickly finds the largest number in an array by spreading all values into Math.max()
.
6. Generate a Random Hex Color
Want a random color in one line using JavaScript?
const randomColor = () => `#${Math.floor(Math.random()*16777215).toString(16)}`;
console.log(randomColor());

This generates a six-digit hex color code, perfect for styling elements dynamically.
7. Convert a String to Title Case
Make the first letter of every word uppercase with this simple JS function:
const toTitleCase = str => str.replace(/\b\w/g, char => char.toUpperCase());
console.log(toTitleCase("hello world")); // Hello World

This replaces the first letter of each word with its uppercase version. Great for formatting dashboard titles!
8. Get the Current Timestamp
No need to struggle with Date
objects—use this shortcut instead:
const timestamp = () => Date.now();
console.log(timestamp());

This returns the number of milliseconds since January 1, 1970. Useful for tracking time events.
9. Convert an Object to a Query String
Turn an object into a URL-friendly query string effortlessly like below:
const toQueryString = obj => new URLSearchParams(obj).toString();
console.log(toQueryString({ name: "John", age: 30 }));
// name=John&age=30

This helps send object data in a URL format, which is useful for APIs and links.
10. Count Occurrences of Elements in an Array
Use reduce()
to count items quickly. Easy right?
const countOccurrences = arr => arr.reduce((acc, item) => ((acc[item] = (acc[item] || 0) + 1), acc), {});
console.log(countOccurrences(["apple", "banana", "apple", "orange"]));
// { apple: 2, banana: 1, orange: 1 }

This creates an object that counts how often each element appears in the array. Great for analytics!
JavaScript One-Liners – List of Code Example:
JavaScript One-Liners | Description |
---|---|
reverseString(str) | Reverses a string |
isEven(num) | Checks if a number is even or odd |
shuffleArray(arr) | Shuffles an array randomly |
uniqueArray(arr) | Removes duplicates from an array |
maxNumber(arr) | Finds the maximum number in an array |
randomColor() | Generates a random hex color |
toTitleCase(str) | Converts a string to title case |
timestamp() | Gets the current timestamp |
toQueryString(obj) | Converts an object to a query string |
countOccurrences(arr) | Counts occurrences of elements in an array |
Why These One-Liners Are Useful
- Saves time: No need to write lengthy functions.
- More readable: Cleaner and easier to understand.
- Performance optimized: Uses JavaScript’s built-in features effectively.
- Beginner-friendly: Great for learning core JS concepts quickly.
Frequently Asked Questions (FAQ)
1. Are JavaScript one-liners efficient?
Yes! Many of these one-liners use optimized built-in JavaScript methods, making our code more concise and efficient.
2. Will these one-liners work in all browsers?
Most of these work in all modern browsers. However, always check browser compatibility if you are using advanced ES6+ features.
3. Can I use these one-liners in real-world projects?
Absolutely! These tricks can simplify your code and make it more readable, especially for small utility JS functions.
4. How can I learn more JavaScript tricks?
Follow our coding blogs, practice with our examples like CodersTechZone, and experiment with different one-liners in your projects!
Conclusion
These JavaScript one-liners can make your coding life easier while keeping your code clean and efficient. Try them out in your next project and impress your friends with your JavaScript mastery! 🧙♂️
🔥 Which one-liner blew your mind the most? Let me know in the comments!
💡 Want more JavaScript tricks? Follow CodersTechZone for more awesome content!
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply