10 JavaScript One-Liners Secrets That Will Blow Your Mind πŸ€―πŸš€

Lokesh Prajapati
5 min read1 day ago

--

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 sets id 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 for FFFFFF).
  • .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?

  1. split("") β†’ Converts the string into an array of characters.
    β€” β€œHello” => [β€œH”, β€œe”, β€œl”, β€œl”, β€œo”]
  2. reverse() β†’ Reverses the array order.
    β€” [β€œo”, β€œl”, β€œl”, β€œe”, β€œH”]
  3. 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! πŸ’¬

--

--

Lokesh Prajapati
Lokesh Prajapati

Written by Lokesh Prajapati

Front-end-developer | Web Designer | Shopify Experts - https://lokesh-prajapati.vercel.app/

No responses yet