10 JavaScript One-Liners Secrets That Will Blow Your Mind π€―π
JavaScript is a powerful and versatile programming language, and if you master smart coding techniques, your development speed and code efficiency can improve significantly. One-liners are short yet powerful code snippets that make common tasks easier and faster.
Today, weβll explore 10 mind-blowing JavaScript one-liners that have real-world applications. If youβre a developer, coder, or JavaScript enthusiast, these tricks will take your coding game to the next level! π₯
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
1οΈβ£ Convert an Array of Objects into a JSON.
π Use Case: When you need to convert API-fetched data into object format, like in user management systems or e-commerce orders.
const users = [{id: 1, name: "Aman"}, {id: 2, name: "Neha"}];
const userObj = Object.fromEntries(users.map(user => [user.id, user]));
console.log(userObj);
// β
Output:
{
"1": {"id": 1, "name": "Aman"},
"2": {"id": 2, "name": "Neha"}
}
π‘ What Did We Learn?
map()
iterates through the array and setsid
as the key.Object.fromEntries()
generates a new object from key-value pairs.
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
2οΈβ£ Remove Duplicates from an Array π₯
π Use Case: When you need to remove duplicate values from product tags, categories, or customer preferences.
const tags = ["sale", "new", "sale", "trending"];
const uniqueTags = [...new Set(tags)];
console.log(uniqueTags);
// β
Output:
[ "sale", "new", "trending" ]
π‘ What Did We Learn?
Set()
automatically removes duplicates.[...Set]
uses the spread operator to convert Set back into an array.
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
3οΈβ£ Swap Two Variables Without a Third Variable π₯
π Use Case: When you need to swap values in form validation or data manipulation.
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b);
// β
Output: 10, 5
π‘ What Did We Learn?
- Uses ES6 destructuring for clean & readable syntax.
- No need for an extra variable.
- Works with any type of variables (numbers, strings, objects).
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
5οΈβ£ Flatten a Nested Array (Multi-Level) π₯
π Use Case: When you need to flatten JSON API responses.
const nestedArr = [1, [2, [3, [4]]]];
const flatArr = nestedArr.flat(Infinity);
console.log(flatArr);
// β
Output:
[1, 2, 3, 4]
β Why use this?
- Easy and readable!
- Supports any depth (
Infinity
ensures full flattening). - Best choice for modern JavaScript (ES2019+).
β Limitation:
- Doesnβt work in older browsers (Polyfill required).
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
6οΈβ£ Generate a Random Hex Color π¨
π Use Case: When you need to generate random colors for UI themes or design applications.
const randomColor = () => "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
console.log(randomColor());
// β
Output: - Any Random Hexa Color Code...
β Why is this the best?
Math.random() * 0xFFFFFF
β Generates a random number between 0 and 16777215 (decimal forFFFFFF
)..toString(16)
β Converts the number to a hexadecimal string..padStart(6, '0')
β Ensures the color always has 6 characters.
π₯ Guaranteed to always return a valid hex color!
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
7οΈβ£ Get the Last Element of an Array π₯
π Use Case: When you need to fetch the last message in chat applications or notifications.
const lastElement = arr => arr.at(-1);
console.log(lastElement([5, 10, 15, 20]));
// β
Output: 20
β Why use this?
- Works with negative indexes.
- Cleaner and more readable.
- Best for modern JavaScript (ES2022+).
β Limitation:
- Doesnβt work in older browsers (Polyfill needed).
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
8οΈβ£ Reverse a String in One Line π₯
π Use Case: When you need to implement CAPTCHA validation or reverse text animation.
const reverseString = str => [...str].reverse().join("");
console.log(reverseString("hello"));
// β
Output: "olleh"
π How Does This Work?
split("")
β Converts the string into an array of characters.
β βHelloβ => [βHβ, βeβ, βlβ, βlβ, βoβ]reverse()
β Reverses the array order.
β [βoβ, βlβ, βlβ, βeβ, βHβ]join("")
β Converts the array back into a string.
β βolleHβ
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
9οΈβ£ Count the Occurrences of Each Element in an Array π₯
π Use Case: When you need to track best-selling products in an e-commerce website.
const countOccurrences = arr => arr.reduce((acc, val) => (acc[val] = (acc[val] || 0) + 1, acc), {});
console.log(countOccurrences(["apple", "banana", "apple", "orange", "banana", "apple"]));
// β
Output: { apple: 3, banana: 2, orange: 1 }
β Why use this?
- Efficient & concise β
- Works for any type of array values β
- No extra loops β
β Limitation:
- Might be less readable for beginners.
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
π Check if an Object is Empty π₯
π Use Case: When you need to validate API responses or form inputs.
const isEmptyObject = obj => Object.keys(obj).length === 0;
console.log(isEmptyObject({}));
console.log(isEmptyObject({ name: "John" }));
// β
Output:
1. True
2. False
β Why use this?
Object.keys(obj)
returns an array of keys.- If length is
0
, the object is empty. - Works in all browsers (including old ones).
β Limitation:
- Only checks own properties, not inherited properties.
β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β β
π Conclusion
Efficiency and readability are crucial in JavaScript. These 10 powerful one-liners will help you write faster, cleaner, and smarter code.
π Which one-liner did you find the most useful? Drop a comment below! π¬